我試圖從一個數據框(在我的示例中是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')
對於迴歸變量必須具有相同的長度。使用'lm(df $ birds〜df [,1])''或lm(birds〜df1 [[as.character(df [1,1])]]],data = df1)' – etienne
Hello @etienne,我不認爲它回答了我的需求,因爲我想將df特定值用作基於df1數據框架的lm函數中的列。是否有任何方法將此值「粘貼」爲文本/串進入lm函數? – mql4beginner
你真的想要運行什麼迴歸?在df1 $ red上預測df1 $鳥? – etienne