简体   繁体   English

是否有用于删除特定列条件的 R 函数

[英]Is there R function for removing specific column condition

Hello all my df looks like你好我所有的 df 看起来像

PID V1
123 1
123 2
123 3
111 1
111 2
111 1
122 3
122 1
122 1
333 1
333 4
333 2

I want to delete rows contains 1 and 2 event alone for the PID我想为PID删除单独包含 1 和 2 事件的行

and expected output和预期输出

PID V1
123 1
123 2
123 3
122 3
122 1
122 1
333 1
333 4
333 2

You can do this in base R :您可以在基础 R 中执行此操作:

subset(df, !ave(V1 %in% 1:2, PID, FUN = all))

#   PID V1
#1  123  1
#2  123  2
#3  123  3
#7  122  3
#8  122  1
#9  122  1
#10 333  1
#11 333  4
#12 333  2

dplyr

library(dplyr)
df %>% group_by(PID) %>% filter(!all(V1 %in% 1:2))

or data.table :或数据data.table

library(data.table)
setDT(df)[, .SD[!all(V1 %in% 1:2)], PID]

The logic of all of them is the same.他们的逻辑都是一样的。 Remove groups ( PID ) who have only 1 and 2 in V1 column.删除V1列中只有 1 和 2 的组 ( PID )。

data数据

df <- structure(list(PID = c(123L, 123L, 123L, 111L, 111L, 111L, 122L, 
122L, 122L, 333L, 333L, 333L), V1 = c(1L, 2L, 3L, 1L, 2L, 1L, 
3L, 1L, 1L, 1L, 4L, 2L)), class = "data.frame", row.names = c(NA, -12L))

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

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