![](/img/trans.png)
[英]Using R, how can I see if any word from a list of words is contained within a group of columns?
[英]R - How would I check to see if columns corresponding to a given group are all equal within a group?
假設我有這樣的數據:
group value
1 0
1 0
1 0
2 1
2 0
3 1
3 0
4 1
4 1
我將如何遍歷“組”的所有值以查看與組相對應的值是否全部相等。 我想要一個僅包含值不相同的組的數據集。 我不確定避免for循環的簡便方法。
你可以做:
tapply(DF$value, DF$group, FUN = function(x) length(unique(x))) > 1L
# 1 2 3 4
# FALSE TRUE TRUE FALSE
要對表進行子集化,請使用ave
編寫相同的內容:
DF[ ave(DF$value, DF$group, FUN = function(x) length(unique(x))) > 1L, ]
# group value
# 4 2 1
# 5 2 0
# 6 3 1
# 7 3 0
對於包,后面的步驟看起來像...
library(data.table)
setDT(DF)[, if (uniqueN(value) > 1L) .SD, by=group]
# or
library(dplyr)
DF %>% group_by(group) %>% filter(n_distinct(value) > 1L)
這是使用table
另一種選擇
tbl <- rowSums(table(df1)>0)>1
subset(df1, group %in% names(tbl)[tbl])
# group value
#4 2 1
#5 2 0
#6 3 1
#7 3 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.