Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Select values from data table in range

Tags:

r

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?

like image 826
poundifdef Avatar asked Mar 05 '11 16:03

poundifdef


People also ask

How do I subset data in range in R?

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)].

How do I select a specific value in a column in R?

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”.


1 Answers

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 
like image 102
Andrie Avatar answered Oct 03 '22 07:10

Andrie