r语言 - 使用索引与数据帧进行连接



我有一个表如下:

tableA <-structure(c(0L, 1L, 2L, 0L, 3L, 0L, 3L, 2L, 0L), dim = c(3L, 
3L), dimnames = structure(list(c("0.3", "0.4", 
"0.6"), c("A", "B", "C")), names = c("", "")), class = "table")
#     A B C
# 0.3 0 0 3
# 0.4 1 3 2
# 0.6 2 0 0
i1 <- structure(c(FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, 
FALSE), dim = c(3L, 3L), dimnames = structure(list(c("0.3", "0.4", 
"0.6"), c("A", "B", "C")), names = c("", "")))
#           A     B     C
#   0.3 FALSE FALSE FALSE
#   0.4  TRUE FALSE  TRUE
#   0.6 FALSE FALSE FALSE

我希望,对于i1TRUE的每个单元格,将"(replaced)"添加到tableA中的值。我从将表转换为字符串值开始。

tableA[] <- lapply(tableA, as.character)

然后执行以下操作:

tableA[i1] <- paste0(tableA[i1], " (replaced)")

返回一个列表。在这种情况下,我应该如何保持表格格式?

lapply返回一个销毁数据帧的列表。没有必要:

tableA <- structure(c(0L, 1L, 2L, 0L, 3L, 0L, 3L, 2L, 0L), dim = c(
3L,
3L
), dimnames = structure(list(c(
"0.3", "0.4",
"0.6"
), c("A", "B", "C")), names = c("", "")), class = "table")
i1 <- structure(c(
FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE,
FALSE
), dim = c(3L, 3L), dimnames = structure(list(c(
"0.3", "0.4",
"0.6"
), c("A", "B", "C")), names = c("", "")))
tableA[i1] <- paste0(tableA[i1], " (replaced)")
tableA
#>      
#>       A            B C           
#>   0.3 0            0 3           
#>   0.4 1 (replaced) 3 2 (replaced)
#>   0.6 2            0 0

相关内容

  • 没有找到相关文章

最新更新