Why is this matrix not numerical? Then `as.numeric` destroys the matrix and returns the vector

I have a data frame with a name input. The first column refers to the article identifier ( ArtID), the subsequent columns will be used to create the matrix.

Based on ArtID, I want R to generate a 2x2 matrix (more accurate: It should be a 2x2 number matrix ). In particular, 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:

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 (it should be).

If applied as.numeric, the matrix is โ€‹โ€‹no longer a 2x2 matrix.

How to get a 2x2 digital matrix?


Minimum 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.numeric(), 2x2.

- ?

+1
2

, . . ,

input <- data.matrix(input)

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)

input <- data.matrix(input)   ## <- this line

stored.matrix = matrix(input[which(ArtID ==i),-1], 2)
is.numeric(stored.matrix)
# [1] TRUE

, ?

input - , input[which(ArtID == i),-1] . . matrix(), .

?matrix, , :

data: an optional data vector (including a list or โ€˜expressionโ€™
      vector).  Non-atomic classed R objects are coerced by
      โ€˜as.vectorโ€™ and all attributes discarded.

, (, is.vector(list(a = 1)) TRUE), matrix.

test <- matrix(list(a = 1, b = 2, c = 3, d = 4), 2)
#     [,1] [,2]
#[1,] 1    3   
#[2,] 2    4   

, class(test) "" ),

str(test)
#List of 4
# $ : num 1
# $ : num 2
# $ : num 3
# $ : num 4
# - attr(*, "dim")= int [1:2] 2 2

typeof(test)
# [1] "list"

, .

.

test <- matrix(list(a = 1, b = 2:3, c = 4:6, d = 7:10), 2)
#     [,1]      [,2]     
#[1,] 1         Integer,3
#[2,] Integer,2 Integer,4

str(test)
#List of 4
# $ : num 1
# $ : int [1:2] 2 3
# $ : int [1:3] 4 5 6
# $ : int [1:4] 7 8 9 10
# - attr(*, "dim")= int [1:2] 2 2

, typeof() ...:)

, - . . , "".
+2

unlist():

matrix(unlist(input[ArtID ==i,-1]),2)

storage.mode(m) <- "numeric"
+4

Source: https://habr.com/ru/post/1651946/


All Articles