[英]Is there an R function for removing a specific snippet of the data in a column?
[英]Is there R function for removing specific column condition
你好我所有的 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
我想為PID
刪除單獨包含 1 和 2 事件的行
和預期輸出
PID V1
123 1
123 2
123 3
122 3
122 1
122 1
333 1
333 4
333 2
您可以在基礎 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))
或數據data.table
:
library(data.table)
setDT(df)[, .SD[!all(V1 %in% 1:2)], PID]
他們的邏輯都是一樣的。 刪除V1
列中只有 1 和 2 的組 ( PID
)。
數據
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.