使用字符串向量逐行粘贴字符串矩阵

时间:2016-06-24 01:20:54

标签: r for-loop matrix paste

我正在尝试将multcompView个字母与摘要数据连接成一个矩阵。我使用for loop来运行各个汇总矩阵单元格,并将它们与各自的字母连接起来。我几乎在那里,但我的矩阵输出原始数据和粘贴的数据(见下文)。

功能:

for (i in 1:nrow(X1))
  tableRow = matrix(c(tableRow,paste(tableRow[i],letters$Letters[i],sep = "")),nrow = 1)

其中:  X1是我的摘要表,tableRowX1的第一行,和 letters包含我要连接的字母。

返回:

[1,] "5.53 ± 0.77" "6.72 ± 1.18" "5.12 ± 0.44"
 "5.24 ± 0.41" "5.53 ± 0.77a" "6.72 ± 1.18a" "5.12 ± 0.44a" "5.24 ± 0.41a"

期望的输出:

[1,]  "5.53 ± 0.77a" "6.72 ± 1.18a" "5.12 ± 0.44a" "5.24 ± 0.41a"

1 个答案:

答案 0 :(得分:1)

这将完成所有工作:

## example matrix
set.seed(0); X <- round(matrix(runif(12), nrow = 4, ncol = 3), 2)

#      [,1] [,2] [,3]
# [1,] 0.90 0.91 0.66
# [2,] 0.27 0.20 0.63
# [3,] 0.37 0.90 0.06
# [4,] 0.57 0.94 0.21

matrix(paste0(X, letters[1:4]), nrow = nrow(X))

#      [,1]    [,2]    [,3]   
# [1,] "0.9a"  "0.91a" "0.66a"
# [2,] "0.27b" "0.2b"  "0.63b"
# [3,] "0.37c" "0.9c"  "0.06c"
# [4,] "0.57d" "0.94d" "0.21d"

对于您的数据,您可以执行以下操作:

matrix(paste0(X1, letters$Letters), nrow = nrow(X1))

备注1

我的例子有一些缺陷。您已将X1作为字符矩阵,而我的示例X是数字。执行paste0()时,数值0.90变为"0.9"(因为as.character(0.90)给出了"0.9")。对于您的数据,将不会出现此类行为。

备注2

哦,我实际上找到了避免这种行为的方法。

X <- format(X)

#      [,1]   [,2]   [,3]  
# [1,] "0.90" "0.91" "0.66"
# [2,] "0.27" "0.20" "0.63"
# [3,] "0.37" "0.90" "0.06"
# [4,] "0.57" "0.94" "0.21"

然后执行paste0()即可:

#      [,1]    [,2]    [,3]   
# [1,] "0.90a" "0.91a" "0.66a"
# [2,] "0.27b" "0.20b" "0.63b"
# [3,] "0.37c" "0.90c" "0.06c"
# [4,] "0.57d" "0.94d" "0.21d"