【问题标题】:R: adding items in a listR:在列表中添加项目
【发布时间】:2015-10-08 04:30:02
【问题描述】:
dput(dat)
list(structure(c(0, 0, -1, -2, -1, -2, -1, -2, 0, 2, 99, 0, -1, 
-2, -1, -2), .Dim = c(2L, 8L), .Dimnames = list(c("type1", "type2"
), c("A", "B", "C", "D", "E", "F", 
"G", "H"))), structure(c(1, 2, 1, 2, 1, 2, 1, 2, 
1, 2, 99, 0, 1, 3, 1, 3), .Dim = c(2L, 8L), .Dimnames = list(
    c("type1", "type2"), c("A", "B", "C", 
    "D", "E", "F", "G", "H"))))

>dat
[[1]]
      A  B  C  D E  F  G  H
type1 0 -1 -1 -1 0 99 -1 -1
type2 0 -2 -2 -2 2  0 -2 -2

[[2]]
      A B C D E  F G H
type1 1 1 1 1 1 99 1 1
type2 2 2 2 2 2  0 3 3

假设我有 2 个项目的上述列表。每个项目由一个 2x8 data.frame 组成。我想要

1) 将 2 个 data.frames 中每一列的 type1 值相加(但将 99 视为 0)

2) 如果type1 值为0,则保留其对应的type2 值。如果type1值不等于0,则设置其type2值=0。

3) 对 data.frames 中每一列的 type2 值求和

4) 计算每列 = 0 的 type1 值的数量并将它们相加(这是 type1_0 行)

结果应该是这样的

            A B C D E F G H
    type1   1 0 0 0 1 0 0 0     
    type2   0 0 0 0 2 0 0 0
  type1_0   1 0 0 0 1 0 0 0

【问题讨论】:

  • 顺便说一句,这些是矩阵,而不是数据框。
  • 你是如何将 type1 的 'A' 设为 0 的。不应该是 1 吗?
  • @akrun 感谢您指出这一点
  • @Stedy 我认为我的主要问题是处理列表中的矩阵。从算法上讲,我想我可能可以处理第 1-4 步,(if(type1 == 0){type2 = type2} else type2 = 0,colsum type2ind = which(type1 == 99); type1[ind] = 0,colsum type1。)这些方面的东西
  • 没看懂最后type1_0行,是不是和type1一样。也许Reduce("+",lapply(dat, function(x) {x[2,][x[1,]!=0] <- 0; replace(x, which(x==99), 0)}))

标签: r list subset


【解决方案1】:

我们循环遍历listlapply(dat,..),将所有不为0的'type1'的第二行('type2')更改为0,replace将99与0相加,并对相应的元素求和与Reduce。我们提取 'type1' 行,即带有lapplyrbind 的第一行,转换为逻辑矩阵(! - 对于 0 返回 TRUE,对于其他值返回 FALSE),得到 colSumsrbind res1'。

res1 <- Reduce("+",lapply(dat, function(x) {
              x[2,][x[1,]!=0] <- 0
              replace(x, which(x==99), 0)}))


res2 <- rbind(res1, type1_0= colSums(!do.call(rbind, lapply(dat, `[`, 1,))))


res2
#        A B C D E F G H
#type1   1 0 0 0 1 0 0 0
#type2   0 0 0 0 2 0 0 0
#type1_0 1 0 0 0 1 0 0 0

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    相关资源
    最近更新 更多