简体   繁体   English

R-从数据框中为向量中的列值设置行

[英]R - subsetting rows from a data frame for column values within a vector

Have a data.frame, df as below 有一个data.frame,df如下

id | name | value
1  | team1 | 3
1  | team2 | 1
2  | team1 | 1
2  | team2 | 4
3  | team1 | 0
3  | team2 | 6 
4  | team1 | 1
4  | team2 | 2 
5  | team1 | 3
5  | team2 | 0 

How do we subset the data frame to get rows for all values of id from 2:4 ? 我们如何子集数据帧以获取所有ID从2:4开始的行?

We can apply conditionally like df[,df$id >= 2 & df$id <= 4] . 我们可以像df[,df$id >= 2 & df$id <= 4]这样有条件地应用。 But is there a way to directly use a vector of integer ranges like ids <- c(2:4) to subset a dataframe ? 但是,是否有一种方法可以直接使用整数范围的向量(例如ids <- c(2:4)来对数据帧进行子集化?

One way to do this is df[,df$id >= min(ids) & df$id <= max(ids)] . 一种实现方法是df[,df$id >= min(ids) & df$id <= max(ids)]

Is there a more elegant R way of doing this ? 有更优雅的R方法吗?

The most typical way is mentioned already, but also variations using match 已经提到了最典型的方式,但也使用了match

with(df, df[match(id, 2:4, F) > 0, ])

or, similar 或类似

with(df, df[is.element(id, 2:4), ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM