[英]In R: How to generate a subset of a data table based on its common elements with two lists of characters
我陷入了这个问题,我不确定哪种方法更有效! 我想根据两个字符列表生成一个数据表:我的第一个 data.table 是:
sample 1 sample 2 N
a b 2
c c 1
b c 3
c d 2
a c 3
d f 1
d h 3
如果列表是:
List1= list('a','b')
List2= list('c')
现在,我想查看“sample1”并根据两个列表找到上述数据表的子集。
我正在寻找的结果是:
sample 1 sample 2 N
a b 2
c c 1
b c 3
c d 2
a c 3
我很感激你在这方面的帮助。
有什么阻止您组合列表然后按结果过滤的吗?
例如:
list <- c(unlist(List1), unlist(List2))
df <- filter(df, `sample 1` %in% list)
DT[`sample 1` %in% unlist(list(List1, List2))]
sample 1 sample 2 N
1: a b 2
2: c c 1
3: b c 3
4: c d 2
5: a c 3
数据
List1 = list('a', 'b')
List2= list('c')
DT <- fread(
"sample 1, sample 2, N
a, b, 2
c, c, 1
b, c, 3
c, d, 2
a, c, 3
d, f, 1
d, h, 3")
我们可以使用base R
subset
subset(df2, sample1 %in% unlist(c(List1, List2)))
df2 <- structure(list(sample1 = c("a", "c", "b", "c", "a", "d", "d"),
sample2 = c("b", "c", "c", "d", "c", "f", "h"), N = c(2L,
1L, 3L, 2L, 3L, 1L, 3L)), class = "data.frame", row.names = c(NA,
-7L))
List1 <- list('a', 'b')
List2 <- list('c')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.