Tinker
Tinker

Reputation: 4545

How can I encapsulate a matrix inside a data frame in R?

I am trying to put data within a dataframe:

> mymatrix <- matrix(seq(1, 12), ncol=4)
> mymatrix
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> myresults <- c(TRUE, FALSE, TRUE)

I would like to encapsulate this within a data frame:

> df <- data.frame(mymatrix, myresults)
> df
  X1 X2 X3 X4 myresults
1  1  4  7 10      TRUE
2  2  5  8 11     FALSE
3  3  6  9 12      TRUE

However, when I try to look up:

> df$mymatrix
NULL

> df$
df$X1         df$X2         df$X3         df$X4         df$myresults
  1. Why is df$mymatrix NULL?
  2. Why did the columns of mymatrix 'leak' into the df$ namespace?

Note: I am trying to create data similar to the yarn package

Upvotes: 4

Views: 89

Answers (1)

akrun
akrun

Reputation: 887213

You can try

  df <- data.frame(mymatrix=I(mymatrix), myresults)
  df$mymatrix
  #     [,1] [,2] [,3] [,4]
  #[1,]    1    4    7   10
  #[2,]    2    5    8   11
  #[3,]    3    6    9   12

  str(df)
  #'data.frame':    3 obs. of  2 variables:
  #$ mymatrix : 'AsIs' int [1:3, 1:4]  1  2  3  4  5  6  7  8  9 10 ...
  #$ myresults: logi  TRUE FALSE TRUE

 lm(mymatrix ~ myresults, data=df)

 #Call:
 #lm(formula = mymatrix ~ myresults, data = df)

 #Coefficients:
 #               [,1]       [,2]       [,3]       [,4]     
 #(Intercept)    2.000e+00  5.000e+00  8.000e+00  1.100e+01
 #myresultsTRUE  2.040e-16  8.158e-16  8.158e-16  2.448e-15

BTW, you don't need to create a 'df' to do this

 lm(mymatrix~myresults)

 #Call:
 #lm(formula = mymatrix ~ myresults)

 #Coefficients:
 #              [,1]       [,2]       [,3]       [,4]     
 #(Intercept)    2.000e+00  5.000e+00  8.000e+00  1.100e+01
 #myresultsTRUE  2.040e-16  8.158e-16  8.158e-16  2.448e-15

Upvotes: 1

Related Questions