2015-11-18 50 views
1

我試圖從一個數據框(在我的示例中是df,第一列中的具體值是「紅色」)提取特定值並且在線性迴歸中使用它作爲一個獨立變量,該線性迴歸基於另一個將此值作爲列的數據框。我將此值保存爲字符,但出現錯誤(描述如下)。我如何將這個值添加到基於另一個數據框的lm函數中?如何將數據幀的特定值添加到基於另一個數據幀的線性迴歸中

df <- read.table(text = " color birds wolfs  
        red   9   7 
        red   8   4 
        red   2   8 
        red   2   3 
        black   8   3 
        black   1   2 
        black   7   16 
        black   1   5 
        black   17  7 
        black   8   7 
        black   2   7 
        green   20  3 
        green   6   3 
        green   1   1 
        green   3   11 
        green   30   1 ",header = TRUE) 

df1 <- read.table(text = " red birds wolfs  
        10   9   7 
        8   8   4 
        11   2   8 
        8   2   3 
        3   8   3 
        4   1   2 
        8   7   16 
        9   1   5 
        10   17  7 
        8   8   7 
        6   2   7  ",header = TRUE) 
# I extracted the desired value than I added it to the new lm function and got an error: 
df[1,1] 
[1] red 
Levels: black green red 
lm<-lm(birds~df[1,1],data=df1) 
Error in model.frame.default(formula = birds ~ df[1, 1], data = df1, drop.unused.levels = TRUE) : 
    variable lengths differ (found for 'df[1, 1]') 
# I also tried to change the value into character : 
b<-as.character(df[1,1]) 
b 
[1] "red" 
lm<-lm(birds~ b ,data=df1) 
but got the same error:Error in model.frame.default(formula = birds ~ b, data = df1, drop.unused.levels = TRUE) : 
    variable lengths differ (found for 'b') 
+0

對於迴歸變量必須具有相同的長度。使用'lm(df $ birds〜df [,1])''或lm(birds〜df1 [[as.character(df [1,1])]]],data = df1)' – etienne

+0

Hello @etienne,我不認爲它回答了我的需求,因爲我想將df特定值用作基於df1數據框架的lm函數中的列。是否有任何方法將此值「粘貼」爲文本/串進入lm函數? – mql4beginner

+0

你真的想要運行什麼迴歸?在df1 $ red上預測df1 $鳥? – etienne

回答

2

我想你可以使用

onValue<-as.character(df[1,1]) # "red" 
reg<-lm(birds~eval(as.symbol(onValue)),data=df1) # regression 

另外,不要你的迴歸指派給名爲lm的對象,因爲它是功能和可能會造成混亂。

eval(as.symbol(onValue))告訴R運行在具有的onValue名稱df1列迴歸(在這種情況下,「紅」)

+0

謝謝@etienne的答案,解釋和小費...... – mql4beginner

2

如果你想爲這一種不同的方法,我覺得update是對於這樣的任務非常好:

#create a formula outside of lm. This can be a simple one against 
#the intercept or one that you already use 
form <- birds ~ 1 

#then add the new variable using paste + update 
#the . ~ . says include everything before and after the tilde ~ 
#that existed in original formula 
form <- update(form, paste('. ~ . + ', df[1,1])) 
#> form 
#birds ~ red 

lm <- lm(form, data=df1) 

Call: 
lm(formula = form, data = df1) 

Coefficients: 
(Intercept)   red 
     2.339  0.462 
+0

謝謝@LyzandeR,Intersting解決方案,作品大。 – mql4beginner

+0

歡迎@ mql4beginner。樂於幫助。 – LyzandeR

相關問題