Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 当与lm一起使用并且想要减少迭代时,Lappy遗漏了一个变量名?_R_Lapply_Lm - Fatal编程技术网

R 当与lm一起使用并且想要减少迭代时,Lappy遗漏了一个变量名?

R 当与lm一起使用并且想要减少迭代时,Lappy遗漏了一个变量名?,r,lapply,lm,R,Lapply,Lm,我使用了melt将我的32列合并为一列,将它们的值合并为一列,将自变量合并为一列 然后我想使用lappy生成一个lm来匹配 年份物种农田 我有两种方法想这样做 1.取一个变量名的lm,即所有年份的椋鸟值(1994:2013) 2.获取所有变量名称的lm,即椋鸟、云雀、蓝翼鸟。。。。农田价值每年都在一起 我的数据示例: structure(list(Years = c(1994L, 1994L, 1995L, 1996L, 1997L, 1998L ), Species = structure(1

我使用了
melt
将我的32列合并为一列,将它们的值合并为一列,将自变量合并为一列

然后我想使用
lappy
生成一个
lm
来匹配
年份物种农田

我有两种方法想这样做
1.取一个变量名的
lm
,即所有年份的椋鸟值(1994:2013)
2.获取所有变量名称的
lm
,即椋鸟、云雀、蓝翼鸟。。。。农田价值每年都在一起

我的数据示例:

structure(list(Years = c(1994L, 1994L, 1995L, 1996L, 1997L, 1998L
), Species = structure(1:6, .Label = c("Starling", "Skylark", 
"YellowWagtail", "Kestrel", "Yellowhammer", "Greenfinch"), class = "factor"), 
    Farmland = c(13260L, 13520L, 8129L, 15575L, 18686L, 18541L
    )), row.names = c(1L, 20L, 40L, 60L, 80L, 100L), class = "data.frame")
另一个例子:

'data.frame':   570 obs. of  3 variables:
 $ Years   : int  1994 1995 1996 1997 1998 1999 2000 2002 2003 2004 ...
 $ Species : Factor w/ 30 levels "Starling","Skylark",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Farmland: int  13260 15551 16335 18997 18571 18376 15770 16054 15101 16276 ...
问题1的lm代码:

df_try <- lapply(1:n, function(x) lm(Farmland ~ Years + Species, work_practice))
这方面的问题;缺少Starling(第一个变量名),结果不需要年份(如何删除),调用时会重复19次,我认为这是因为数据帧。有没有办法只叫它一次


当变量(物种)在列中时,我尝试过这样做,但输出只调用一个变量19次…

这里的问题是,如果
r
必须使用
物种中的所有回归器来估计模型,那么我们将达到完美的共线性。我将使用
data.table::dcast
物种
转化为假人:

df <- structure(list(Years = c(1994L, 1994L, 1995L, 1996L, 1997L, 1998L
), Species = structure(1:6, .Label = c("Starling", "Skylark", 
                                       "YellowWagtail", "Kestrel", "Yellowhammer", "Greenfinch"), class = "factor"), 
Farmland = c(13260L, 13520L, 8129L, 15575L, 18686L, 18541L
)), row.names = c(1L, 20L, 40L, 60L, 80L, 100L), class = "data.frame") 

dfDummies <- suppressWarnings(data.table::dcast(df, Years + Farmland ~ Species, fun.aggregate=function(x) 1, fill=0))
请注意,假人是如何相互排斥的:

> rowSums(dfDummies[, as.character(df[["Species"]])])
[1] 1 1 1 1 1 1
这意味着截距可以写成
种类
二进制变量的线性组合
R
知道这一点,它会悄悄地从估计中删除其中一列——完美的共线性使得不可能找到OLS问题的唯一解决方案

关于完美共线性的更多信息

我不知道您为什么在这里使用
lappy()
。如果您只有一个
data.frame
,并且您对使用所有观测值估计特定模型感兴趣,那么您可以运行:

lm(formula = Farmland ~ Years + Species, df)
> rowSums(dfDummies[, as.character(df[["Species"]])])
[1] 1 1 1 1 1 1
lm(formula = Farmland ~ Years + Species, df)