如何找到符合多个条件的R列表的索引

4
假设我在R中有以下数据框:
set.seed(5)
PosActions <- c("Work","Pause","Clockin","Clockout","Lunch")
df <- data.frame(ID = c(rep(1,3),rep(2:3,each=4),rep(4,5)), 
                 ACTION = sample(PosActions,16,replace=T))

这将返回

   ID   ACTION
1   1    Pause
2   1 Clockout
3   1    Lunch
4   2    Pause
5   2     Work
6   2 Clockout
7   2  Clockin
8   3    Lunch
9   3    Lunch
10  3     Work
11  3    Pause
12  4  Clockin
13  4    Pause
14  4  Clockin
15  4    Pause
16  4    Pause

在这个数据框中,对应于ID == 2和ID == 3(第4行到第11行),在ACTION列中包含字符串“Work”。我正在尝试找到这些行的索引。在这种情况下:
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
[14] FALSE FALSE FALSE

换句话说,每当具有相同 ID 号的一组行在“ACTION”列中包含“Work”时,必须返回该 ID 号的所有行索引。
希望有人能帮助我,提前感谢。
1个回答

4
您的问题不是很清楚。看起来您正在寻找以下内容:
> df$ID %in% df$ID[which(df$ACTION == "Work")]
 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
[11]  TRUE FALSE FALSE FALSE FALSE FALSE

逐步操作:

## Which rows have "Work" in the "ACTION" column?
> which(df$ACTION == "Work")
[1]  5 10

## What's the corresponding "ID" value, so we can subset on that?
> df$ID[which(df$ACTION == "Work")]
[1] 2 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接