J.Con
J.Con

Reputation: 4307

Pasting a string matrix row-wise with a string vector

I am trying to concatenate multcompView letters with summary data into a matrix. I am using a for loop to run through the individual summary matrix cells and concatenate these with their respective letters. I am almost there but my matrix outputs both the original data and the pasted data (see below).

Function:

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

Where: X1 is my summary table, tableRow is the first row of X1, and letters contains the letter I want to concatenate with.

Returns:

[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"

Desired output:

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

Upvotes: 0

Views: 930

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73415

This will do all the work:

## 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"

For your data, you can do:

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

Remark 1

My example here has some defect. You already have X1 as a character matrix, while my example X is numeric. When doing paste0(), numerical value 0.90 becomes "0.9" (because as.character(0.90) gives "0.9"). For your data there will be no such behaviour.

Remark 2

Oh, I actually find a way to avoid such behaviour.

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"

Then doing paste0() is OK:

#      [,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"

Upvotes: 1

Related Questions