【问题标题】:R-constructing a list, which is semi-subset of a list conditional to another listR-构造一个列表,它是一个列表的半子集,以另一个列表为条件
【发布时间】:2015-03-15 18:56:54
【问题描述】:

让我有两个列表(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

想要的输出 list3 是:

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”,则在list3中相关每个数据框的每一列的末尾添加0。

如何使用 R 来做到这一点?我会很高兴得到任何帮助。非常感谢。

【问题讨论】:

  • 请发布创建这种结构的代码,或使用 dput 发布您正在使用的示例。 (您已经尝试过自己的示例,对吗?)

标签: r


【解决方案1】:
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

【讨论】:

  • 感谢您的帮助。但是您的代码并没有做我想要的确切事情。我知道,我不能很清楚地说明这个问题。我想在每列数据帧的末尾添加 0。我编辑了 list2 的值。你能尝试新的价值观吗?再次非常感谢。
  • 现在有点复杂了。检查这是否是您想要的代码
  • 非常感谢您节省时间。您的代码非常适用于 2x2 矩阵。但对于一般矩阵,它不起作用。不说出来是我的错。我需要一种用于通用矩阵的方法(数据帧列表中的所有数据帧长度相同,但大小可以是任何值,而不仅仅是 2x2)。你的解决方案让我受益匪浅。我会努力的。再次非常感谢。
  • 我编辑了答案(ind_fin 的代码),现在它应该适用于更一般的情况,而不仅仅是2x2 矩阵。您只需要相应地调整l_zero。检查一下,如果有任何问题,请告诉我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 2021-01-04
  • 1970-01-01
相关资源
最近更新 更多