How to delete all lines belonging to a certain group when only one line fulfills a condition in R?

Below is my dataset:

> 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 identifiers of vehicles included in a particular segment of the highway. They were observed until they left the segment, so each car has a different number of time frames in which it was observed. Frame numbers are shown in the column frame.id. The third column indicates whether the vehicle has changed in the lane and in which frame. In this example, the data all but vehicle number 2 changed lane. Car number 5 twice changed lane.

Required

, . subset(lanec, lane.change!='yes'), , lane.change yes. , :

vehicle.id frame.id lane.change
1           2        1           .
2           2        2           .
3           2        3           .
4           2        4           .
5           2        5           .

? , . .

+2
2

:

subset(lanec, ave(lane.change != "yes", vehicle.id, FUN = all))

, ave, , :

lanec <- transform(lanec, stays.in.lane = ave(lane.change != "yes", vehicle.id, FUN = all))
subset(lanec, stays.in.lane)

, ave TRUE/FALSE lanec: vehicle.id (, all) lane.change, 'yes'.

0
 steady <- names( which(with(lanec, tapply(lane.change, vehicle.id, function(x) all(x==".")) ) ))
steady
[1] "2"

, , 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           .
0

Source: https://habr.com/ru/post/1675961/


All Articles