R:在列表中添加项目
R: adding items in a list
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
我们遍历 list
(lapply(dat,..
),将第二行 ('type2') 更改为 0,因为所有 'type1' 不是 0,replace
将99加0,将对应的元素加Reduce
。我们提取 'type1' 行,即具有 lapply
、rbind
的第一行,转换为逻辑矩阵(!
- returns TRUE 表示 0,FALSE 表示其他值) , 得到 colSums
和 rbind
与 '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
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
我们遍历 list
(lapply(dat,..
),将第二行 ('type2') 更改为 0,因为所有 'type1' 不是 0,replace
将99加0,将对应的元素加Reduce
。我们提取 'type1' 行,即具有 lapply
、rbind
的第一行,转换为逻辑矩阵(!
- returns TRUE 表示 0,FALSE 表示其他值) , 得到 colSums
和 rbind
与 '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