我有一个包含10000行和14个变量的数据框(data2):
treat rep dist time0 time10 N2O10 WC Temp
1 AGP 1 0 10:09:00 10:19:00 0.2270316 12 17.1
time20 N2O20 N2O0 t0 t10 t20
1 10:31:00 0.3479662 0.2395295 0 0.1666667 0.3666667
我想进行线性回归并获得数据框中每行的斜率,其中x是t0,t10和t20,y是N2O0,N2O10和N2O20。 就像数据框中一行的这个例子一样:
data3<-data2[1,]
with (data3, lm(c(N2O0,N2O10,N2O20)~c(t0,t10,t20)))
当我尝试在“apply”中使用上述函数作为匿名函数时,我收到了一条错误消息。
data4<-apply(data2, 1, function(data2) lm(c(data2$N2O0,data2$N2O10,data2$N2O20)~c(data2$t0,data2$t10,data2$t20))$coefficients[2])
eval中的错误(substitute(expr),data,enclos = parent.frame()):
'character'类型的无效'envir'参数
我不知道这意味着什么,并且会对如何纠正这条线的任何建议感到高兴。
答案 0 :(得分:0)
我建议:
list
。{/ li>中创建apply
lm
。尝试:
apply(data2[c("N2O0","N2O10","N2O20", "t0","t10","t20")], 1, function(x) {
temp <- as.list(x)
lm(c(N2O0, N2O10, N2O20) ~ c(t0, t10, t20), data = temp)$coefficients[2]
})
# 1
# 0.3059211
您遇到此问题的部分原因是当您使用apply
时,由于&#34;对待&#34;,&#34; time0&#34,所有值都会变为字符;,&#34; time10&#34;和&#34; time20&#34;列。
比较
> apply(data2, 1, function(data2) sum(data2[1]))
Error in sum(data2[1]) : invalid 'type' (character) of argument
> apply(data2[-c(1, 4, 5, 9)], 1, function(data2) sum(data2[1]))
1
1
示例数据:
data2 <- structure(list(treat = "AGP", rep = 1L, dist = 0L, time0 = "10:09:00",
time10 = "10:19:00", N2O10 = 0.2270316, WC = 12L, Temp = 17.1,
time20 = "10:31:00", N2O20 = 0.3479662, N2O0 = 0.2395295,
t0 = 0L, t10 = 0.1666667, t20 = 0.3666667), .Names = c("treat",
"rep", "dist", "time0", "time10", "N2O10", "WC", "Temp", "time20",
"N2O20", "N2O0", "t0", "t10", "t20"), row.names = "1", class = "data.frame")