2016-02-05 146 views
0

这是R问题,而不是统计问题。R编程中lm()中因变量的类型无效

我想在R中执行一组20个独立变量和1个因变量的多元线性回归。 20个独立变量位于一个csv文件中,1个独立变量位于另一个csv文件中。每个文件中的每一行对应于一天的一次测量。

我设法用read.csv(...)将20个独立变量导入一个名为“预测变量”的变量中。然后,我再次使用read.csv(...)将依赖测量导入到名为“dependent”的(变量?)中。但是当我使用lm(依赖于〜X1 + X2 + X3 + X4 + X5 + X6 + X7 + X8 + X9 + X10 + X11 + X12 + X13 + X14 + X15 + X16 + X17 + X18 + X19 + X20)

(注:X_1,...,X20都列在该CSV文件中的预测)

我得到的错误标题:

Error in model.frame.default(formula = dependent ~ X1 + X2 + X3 + X4 + X5 + : invalid type (list) for variable 'dependent'

我不明白什么会出错?

的预测文件看起来像(但到X20)

enter image description here

和依赖CSV文件看起来像

enter image description here

+0

尝试因变量添加为一列数据框以及独立变量。 –

+0

从你的错误的样子,我要说的是,依赖是一个列表。如果你有一个有21列的数据框会更好:你的20个X和因变量。然后,运行回归会很容易。您可以查看'cbind'来追加2个数据框 – etienne

+1

向我们展示您在R中使用的数据结构(导入后)。来自excel的数据很好,但并没有说明整个故事。有关如何呈现数据的信息,请参阅http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example(提示:'str()')。 –

回答

1

让我们对DF一些随机数据:

df<-replicate(5,rnorm(20)) 
names<-paste0('X',1:5) 
colnames(df)<-names 

依赖于评论已经给出,所以我们可以用cbind创建一个数据帧:

newDf<-cbind(dependent,df) 

head(newDf) 
# dependent   X1   X2   X3   X4   X5 
# 1 0.49295341 -1.728304515 0.9902622 0.6164557 0.904435464 -0.65801021 
# 2 0.04331689 0.641830028 2.3829267 0.6165678 0.002691661 0.85520221 
# 3 0.53106346 -1.529310531 0.6644159 -1.6921015 -1.176692158 1.15293623 
# 4 0.06983530 0.001683688 0.2073812 0.3687421 -1.318220727 0.27627456 
# 5 0.74574779 0.250247821 -2.2106331 0.9678592 -0.592997366 0.14410466 
# 6 0.56349179 0.563867390 2.6917140 1.2765787 0.797380501 -0.07562508 

然后,我们可以运行回归:

lm(dependent~.,newDf) # . selects all the other columns of newDf 

# Call: 
# lm(formula = dependent ~ ., data = newDf) 

# Coefficients: 
# (Intercept)   X1   X2   X3   X4   X5 
#  0.50522  -0.09975  -0.03040  0.06431  -0.00398  -0.09596