Home > Blockchain >  How can I assign a matrix to a observation in a data frame in R
How can I assign a matrix to a observation in a data frame in R

Time:01-15

I am trying to create a dataframe where one of the columns is essentially a list of matrices, but I am unsure how to do that. My code is essentialy so:

matrix <- matrix(1:45, 18,18)
df$column[observation] <- matrix

This does not work at all, with the observation taking one number as its value, instead of the entire matrix

CodePudding user response:

You can put inside the column as a list, an example:

Code

matrix <- matrix(1:45, 18,18)

df <- data.frame(a = 1)

df$m <- list(matrix)

str(df)

Output

'data.frame':   1 obs. of  2 variables:
 $ a: num 1
 $ m:List of 1
  ..$ : int [1:18, 1:18] 1 2 3 4 5 6 7 8 9 10 ...

CodePudding user response:

As a follow up questions, would you perhaps know how to access a specific element of the list?

You can access elements of the matrices in your list by using index numbers:

m1 <- matrix(1:20, ncol = 4)
m2 <- 5 * m1
m3 <- 10 * m2
list1 <- list(m1, m2, m3)
list1[[2]][3, 3]
# From matrix 2 in the list, get the element indexed at 3, 3
[1] 65
  •  Tags:  
  • r
  • Related