I have a data frame called input
. The first column refers to an Article ID (ArtID
), the subsequent columns will be used to create the matrix.
Based on the ArtID
, I want R to generate a 2x2 matrix (more precise: It needs to be a numeric 2x2 matrix). Specifically, I want to create a matrix for the first row (ArtID == 1
), the second row(ArtID == 2
) and so on...
What I came up with so far is this:
for(i in 1:3) {stored.matrix = matrix(input[which(ArtID ==i),-1],nrow = 2)
This gives me a 2x2 matrix, but it is not numeric (which it needs to be).
If I apply as.numeric
, the matrix is no longer a 2x2 matrix.
How do I get a 2x2 numerical matrix?
Minimal reproducible example:
ArtID = c(1,2,3)
AC_AC = c(1,1,1)
MKT_AC = c(0.5,0.6,0.2)
AC_MKT = c(0.5,0.6,0.2)
MKT_MKT = c(1,1,1)
input = data.frame(ArtID, AC_AC, MKT_AC, AC_MKT, MKT_MKT)
stored.matrix = matrix(input[which(ArtID ==i),-1],nrow = 2)
# [,1] [,2]
#[1,] 1 0.5
#[2,] 0.5 1
is.numeric(stored.matrix)
# [1] FALSE
as.numeric(stored.matrix)
## [1] 1.0 0.5 0.5 1.0
As you can see after applying as.numeric()
the matrix is no longer 2x2.
Can anyone help?