I have a data table in R:
name date ---- ---- John 1156649280 Adam 1255701960 ...etc...
I want to get all of the rows that have a date within a range. In SQL, I might say SELECT * FROM mytable WHERE date > 5 AND date < 15
What is the equivalent in R, to select rows based on the range of values in a particular column?
table object using a range of values, we can use single square brackets and choose the range using %between%. For example, if we have a data. table object DT that contains a column x and the values in x ranges from 1 to 10 then we can subset DT for values between 3 to 8 by using the command DT[DT$x %between% c(3,8)].
If you want to use dplyr to select a column in R you can use the select() function. For instance, select(Data, 'Column_to_Get') will get the column “Column_to_Get” from the dataframe “Data”.
Construct some data
df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )
Extract exact matches:
subset(df, date==3) name date 1 John 3
Extract matches in range:
subset(df, date>4 & date<6) name date 2 Adam 5
The following syntax produces identical results:
df[df$date>4 & df$date<6, ] name date 2 Adam 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With