我有两个数据帧单元格和支持(如下所示)。我需要使用以下条件的“cell”子集:所有与向量b元素匹配的“支持”行。我的输出将由所有这些行“单元格”组成。
a<-c(0,1,0)
b<-c(0,0,1)
level = c(3,2,4)
zero = c(1,2,1)
cell <- do.call(expand.grid, lapply(level, seq)) #create all cell
support <- t(apply(cell, 1, function(x) +(x != zero)))
> cell
Var1 Var2 Var3
1 1 1 1
2 2 1 1
3 3 1 1
4 1 2 1
5 2 2 1
6 3 2 1
7 1 1 2
8 2 1 2
9 3 1 2
10 1 2 2
11 2 2 2
12 3 2 2
13 1 1 3
14 2 1 3
15 3 1 3
16 1 2 3
17 2 2 3
18 3 2 3
19 1 1 4
20 2 1 4
21 3 1 4
22 1 2 4
23 2 2 4
24 3 2 4
> support
Var1 Var2 Var3
[1,] 0 1 0
[2,] 1 1 0
[3,] 1 1 0
[4,] 0 0 0
[5,] 1 0 0
[6,] 1 0 0
[7,] 0 1 1
[8,] 1 1 1
[9,] 1 1 1
[10,] 0 0 1
[11,] 1 0 1
[12,] 1 0 1
[13,] 0 1 1
[14,] 1 1 1
[15,] 1 1 1
[16,] 0 0 1
[17,] 1 0 1
[18,] 1 0 1
[19,] 0 1 1
[20,] 1 1 1
[21,] 1 1 1
[22,] 0 0 1
[23,] 1 0 1
[24,] 1 0 1
> hD<-lapply(1:nrow(cell), function (x) cell[which(sum(support[x,]==b)==3),])
> do.call(rbind, hD)
Var1 Var2 Var3
1 1 1 1
2 1 1 1
3 1 1 1我试着使用lapply,但是我没有得到预期的输出。我的输出应该是单元格(如下所示)的第10行、第16行和第22行,支持的第10行、第16行和第22行与向量b完全匹配。我不想使用任何循环。
Var1 Var2 Var3
1 1 2 2
2 1 2 3
3 1 2 4发布于 2020-09-20 11:03:27
这是另一个R基选项
subset(cell,Reduce(`&`,as.data.frame(t(t(support)==b))))或
subset(cell,Reduce(`&`,as.data.frame(support == t(replicate(nrow(support),b)))))这给
Var1 Var2 Var3
10 1 2 2
16 1 2 3
22 1 2 4发布于 2020-09-20 18:21:21
我们也可以
cell[!rowSums(support != b[col(support)]),]
# Var1 Var2 Var3
#10 1 2 2
#16 1 2 3
#22 1 2 4发布于 2020-09-20 10:51:03
您可以将b值与support中的每一行进行比较,方法是转换它,并在cell中选择所有值匹配的行。
cell[colSums(t(support) == b) == length(b), ]
# Var1 Var2 Var3
#10 1 2 2
#16 1 2 3
#22 1 2 4这也可以使用sweep来完成:
cell[rowSums(sweep(support, 2, b, `==`)) == length(b), ]为了与a和b进行比较,我们可以单独匹配它们:
cell[colSums(t(support) == b) == length(b) |
colSums(t(support) == a) == length(a), ]或者使用lapply:
cell[Reduce(`|`, lapply(list(a, b), function(x)
colSums(t(support) == x) == length(x))), ]https://stackoverflow.com/questions/63978085
复制相似问题