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

SelectRRows

Select Problem Overview


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

Select Solutions


Solution 1 - Select

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

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

Solution 2 - Select

You can also do

subset(df, aged <= laclen)

Solution 3 - Select

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBazonView Question on Stackoverflow
Solution 1 - Selectwkmor1View Answer on Stackoverflow
Solution 2 - SelectJonathan ChangView Answer on Stackoverflow
Solution 3 - SelectEnrique Pérez HerreroView Answer on Stackoverflow