如何找到满足多个条件的R列表的索引 [英] How to find the indices of an R list meeting multiple criteria

查看:200
本文介绍了如何找到满足多个条件的R列表的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在R中具有以下数据框:

Suppose I have the following data frame in 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".我试图找到这些行的索引.在这种情况下:

In this data frame, the rows corresponding to ID == 2 and ID == 3 (rows 4 up to 11) contain the string "Work" in the column ACTION. I am trying to find the indices of these rows. In this case:

 [1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
[14] FALSE FALSE FALSE

换句话说,每当具有相同ID号的一组行在ACTION列中包含工作"时,都必须返回此ID号的所有行索引.

In other words, whenever a set of rows with the same ID number contains "Work" in the ACTION column, all row indices of this ID number have to be returned.

我希望有人能帮助我,谢谢.

I hope someone can help me, thanks in advance.

推荐答案

您的问题并不十分清楚.听起来您在寻找以下内容:

Your question isn't totally clear. It sounds like you're looking for the following:

> 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


逐步:


Step by step:

## 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

这篇关于如何找到满足多个条件的R列表的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆