2015-07-06 67 views
4

我試圖把數據幀中的數據:如何在R中的數據框內封裝一個矩陣?

> 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) 

我想一個數據幀中封裝此:

> 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 

然而,當我嘗試查找:

> df$mymatrix 
NULL 

> df$ 
df$X1   df$X2   df$X3   df$X4   df$myresults 
  1. 爲什麼是df $ mymatrix NULL
  2. 爲什麼mymatrix的列'泄露'到df$名稱空間中?

注:我想創建一個類似於紗包

+0

@akrun只想能夠做到做'爲MyModel < - LM(myMatrix的〜myresults,數據= DF)'像像'爲MyModel <樣本數據包'yarn' - LM(NIR〜密度,數據=紗線)' – Sparrowcide

回答

1

數據您可以嘗試

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,你不需要創建一個「DF」要做到這一點

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 
+1

是的謝謝你! – Sparrowcide