Hi all,

I have a matrix as shown below. Is there a way to add additional column that is calculated through a for loop only. For example

``````MatrixA
[,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    a    8
[3,]    3    6    9
``````

Expected. Adding 4 th column to a matrix that is the result of first and second column.

``````MatrixA
[,1] [,2] [,3]   [,4]
[1,]    1    4    7    5 is the result
[2,]    2    a    8    Error in 2 + "a" : non-numeric argument to binary operator is the result
[3,]    3    6    9    9 is the result
``````

Above summation should be done using for loop. For example, something like below

``````for (i in 1:nrow(MatrixA)) {
as[[i]] <- paste0(MatrixA[i,1] +MatrixA[i,2], "is the result")
}
``````

You can create your matrix like so:

``````X = matrix(data = c(1, 4, 7, 2, "a", 8, 3, 6, 9), nrow = 3, ncol = 3, byrow = TRUE)
``````

Yielding:

``````> X
[,1] [,2] [,3]
[1,] "1"  "4"  "7"
[2,] "2"  "a"  "8"
[3,] "3"  "6"  "9"
``````

where

``````> str(X)
chr [1:3, 1:3] "1" "2" "3" "4" "a" "6" "7" "8" "9"
``````

Note, how the data type is `chr` for all entries, including the numbers. You cannot mix data types in a matrix, see R4DS chapter 20.4.1 Coercion

Thanks..... will check

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.