[英]How to remove all rows belonging to a particular group when only one row fulfills the condition in R?
Following is my sample data set: 以下是我的示例数据集:
> dput(lanec)
structure(list(vehicle.id = c(2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
5L, 5L), frame.id = c(1L, 2L, 3L, 4L, 5L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 6L, 7L, 8L, 9L, 10L, 11L,
12L), lane.change = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L), .Label = c(".", "yes"), class = "factor")), .Names = c("vehicle.id",
"frame.id", "lane.change"), class = "data.frame", row.names = c(NA,
-26L))
The first column is the IDs of vehicles entering on a particular segment of a freeway. 第一列是进入高速公路特定路段的车辆ID。 They were observed until they left the segment so each vehicle has different number of time frames in which it was observed. 一直观察到它们离开路段,因此每辆车都有不同的观察时间范围。 The frame numbers are given in frame.id
column. 帧号在frame.id
列中给出。 The third column tells whether the vehicle changed the lane and in which frame. 第三列告诉车辆是否改变了车道以及在哪一帧。 In this sample data all except vehicle # 2 changed the lane. 在此样本数据中,除2号车辆外,所有其他车辆均改变了车道。 Vehicle # 5 changed the lane twice. 5号车两次改变了车道。
I want to identify which vehicles changed the lane and remove them from data set. 我想确定哪些车辆改变了车道,并将其从数据集中删除。 I tried using subset(lanec, lane.change!='yes')
but it only remove those rows where the value of lane.change
is yes
. 我试过使用subset(lanec, lane.change!='yes')
但是它只删除了lane.change
值为yes
那些行。 Using the sample data set, the desired output should be: 使用样本数据集,所需的输出应为:
vehicle.id frame.id lane.change
1 2 1 .
2 2 2 .
3 2 3 .
4 2 4 .
5 2 5 .
How can I achieve this? 我该如何实现? It must be simple but I can't figure it out. 它必须很简单,但我无法弄清楚。 Thanks in advance. 提前致谢。
steady <- names( which(with(lanec, tapply(lane.change, vehicle.id, function(x) all(x==".")) ) ))
steady
[1] "2"
So pick the onew where all the items in lane.change are "." 因此,选择lane.change中所有项目均为“。”的一个。
lanec[ lanec$vehicle.id %in% steady, ]
#-------
vehicle.id frame.id lane.change
1 2 1 .
2 2 2 .
3 2 3 .
4 2 4 .
5 2 5 .
You can do: 你可以做:
subset(lanec, ave(lane.change != "yes", vehicle.id, FUN = all))
To help understand what ave
returns, maybe you can break it into a couple steps: 为了帮助理解ave
回报,也许您可以将其分为几个步骤:
lanec <- transform(lanec, stays.in.lane = ave(lane.change != "yes", vehicle.id, FUN = all))
subset(lanec, stays.in.lane)
You will see that ave
returns a vector of TRUE/FALSE along lanec
: whether the vehicle.id
had all (hence the use of all
) of its lane.change
values not equal to 'yes'
. 你会看到, ave
返回TRUE / FALSE沿矢量lanec
:在是否vehicle.id
了所有(因此使用的all
其) lane.change
值不等于'yes'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.