让我有两个列表(list1和list2),其中每个元素都是数据框:
list1[1]
col1 col2
12 3
9 5
list1[2]
col1 col2
4 11
10 7
list2[1]
col1 col2
b b
b a
list1[2]
col1 col2
a b
b a
所需的输出列表3是:
list3[1]
col1 col2
0 5
0 0
list3[2]
col1 col2
4 7
0 0
即,在list3中,
第i个数据帧等于list1中第i个数据帧的值,条件是list2中的第i个数据帧等于" a"。
但是,如果元素list2不等于" b",则0添加list3中相关每个数据帧的每一列的结尾。
我怎样才能做到这一点?我会很高兴得到任何帮助。非常感谢。
答案 0 :(得分:2)
list1 <- list(data.frame(col1 = c(12, 9), col2 = c(3, 5)), data.frame(col1 = c(4, 10), col2 = c(11, 7)))
list2 <- list(data.frame(col1 = c("b", "b"), col2 = c("b", "a")), data.frame(col1 = c("a", "b"), col2 = c("b", "a")))
#Generate a list of matrices with the coordinates of "a"
ind <- lapply(list2, function(x) which(x == "a", arr.ind = TRUE))
ind_fin <- lapply(ind, function(x) cbind(along = ave(x[,2], x[,2], FUN = seq_along), x[,2]))
# Generate a list of zero matrices, where you will replace some values
l_zero <- replicate(2,matrix(0,2,2),simplify=FALSE)
# Extract the values you want to put into the other matrix
res <- Map(function(x, y) y[x], x = lapply(list2, function(x) x == "a"), y = list1)
最后在here
的帮助下Map("[<-", l_zero, ind_fin, res)
[[1]]
[,1] [,2]
[1,] 0 5
[2,] 0 0
[[2]]
[,1] [,2]
[1,] 4 7
[2,] 0 0