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

走远了吗. 提交于 2020-01-10 06:48:28

问题


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


回答1:


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

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




回答2:


You can also do

subset(df, aged <= laclen)



回答3:


If you use dplyr package you can do:

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


来源:https://stackoverflow.com/questions/2854625/select-only-rows-if-its-value-in-a-particular-column-is-less-than-its-value-in-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!