Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only rows if its value in a particular column is less than the value in the other column

Tags:

select

r

rows

I am using R and need to select rows with aged (age of death) less than or equal to laclen (lactation length). I am trying to create a new data frame to only include rows/ids whereby the value of column'aged' is less than its corresponding 'laclength' value.

df:  id1   id2    laclen    aged 9830  64526    26       6  7609  64547    28       0  9925  64551     3       0  9922  64551     3       5  9916  64551     3       8  9917  64551     3       8  9914  64551     3       2  

the new data frame should look like this:

dfnew: id1   id2    laclen    aged 9830  64526    26       6  7609  64547    28       0  9925  64551     3       0  9914  64551     3       2 

Any help would be appreciated!

Bazon

like image 426
Bazon Avatar asked May 18 '10 04:05

Bazon


People also ask

How do I get the value of a column based on another column value?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.

How do you select rows with certain values in Excel?

➤ Select select_rows_with_given_data from the Macro name box and click on Run. It will open a custom box. ➤ In the Please Enter the Search data box type the specific data and click on OK. As a result, you will see, all the rows which contain the specific data in one of its cells are selected.


2 Answers

df[df$aged <= df$laclen, ]  

Should do the trick. The square brackets allow you to index based on a logical expression.

like image 133
wkmor1 Avatar answered Sep 20 '22 14:09

wkmor1


You can also do

subset(df, aged <= laclen) 
like image 43
Jonathan Chang Avatar answered Sep 21 '22 14:09

Jonathan Chang