背景
我最近问这个问题 https://stackoverflow.com/questions/72899527/replacing-a-subset-of-table-values-with-a-list-of-vectors。然而,我使示例有点过于简单,因此我在这里添加了一些复杂性,其中向量长度不再等于表长度。
Problem
我有一个表如下:
tableA <- structure(c(1L, 0L, 0L, 0L, 4L, 6L, 0L, 6L, 1L, 3L, 0L, 0L, 0L, 0L, 1L), dim = c(3L,
5L), dimnames = structure(list(c("X", "Y",
"Z"), c("A", "B", "C","D", "E")), names = c("", "")), class = "table")
A B C D E
X 1 0 0 3 0 (two positive numbers)
Y 0 4 6 0 0 (two positive numbers)
Z 0 6 1 0 1 (three positive numbers)
向量列表如下:
listB <- list(
"X" = c(0, 4),
"Y" = c(4, 5),
"Z" = c(7, 1, 0))
向量不相等,但向量中数字的数量相等positive表中的数字。
我想替换中的所有值tableA
, 列数B,C, and D
,大于零,对应的值为listB
.
期望的输出:
A B C D E
X 1 0 0 4 0
Y 0 4 5 0 0
Z 0 7 1 0 1
之前的回答
The sindri_baldur 的原始答案 https://stackoverflow.com/a/72899779/8071608建议如下:
cols2replace = match(c('B', 'C', 'D'), colnames(tableA))
cells2replace = tableA[, cols2replace] > 0
tableB = matrix(unlist(listB), nrow = 3, byrow = TRUE)
tableA[, cols2replace][cells2replace] = tableB[, cols2replace][cells2replace]
然而,在我的实际数据中,向量列表中的向量是不相等的。所以:
tableB = matrix(unlist(listB), nrow = 3, byrow = TRUE)
不起作用。
建议
我想知道我是否不能简单地从中获得所有积极的价值观tableA
,将它们替换为 of 的所有正值listB
(这样的值是0
in listB
不被替换),然后将它们放回表中。我开始如下:
# Get all positive values from the table
library(dplyr)
library(tidyr)
library(stringr)
out <- tableA %>%
pivot_longer(cols = -rn) %>%
filter(str_detect(value, '\\b0\\b', negate = TRUE)) %>%
group_by(rn) %>%
summarise(freq = list(value), .groups = 'drop')
但该代码不适用于表格。