上一篇文章:enter link description here
我想根据条件length
计算两个函数。当lst
自变量为<=4
时,当scale
自变量> 4时,一个函数为lm
,第二个函数为length
模型,我尝试使用:
lapply(lst, function (x) ifelse((sapply(lst,length)<=4)==T,scale,
(fit <- lm(x ~ poly(seq(1:length(x)), 5, raw=TRUE)))
(d <- resid(fit)-mean(resid(fit)))/sd(resid(fit))))
但是有一个错误:
ifelse((sapply(lst,length)<= 4)== T,scale,(fit <-lm(x〜: 未使用的参数(d <-resid(fit)-Mean(resid(fit))/ sd(resid(fit)))
当长度大于4时,如何计算同一函数中残差的拟合和z.score?
数据
lst <- list(a=c(2.5,9.8,5.0,6.7,6.5,5.2,34.4, 4.2,39.5, 1.3,0.0,0.0,4.1,0.0,0.0,25.5,196.5, 0.0,104.2,0.0,0.0,0.0,0.0,0.0),
b=c(147.4,122.9,110.2,142.3))
答案 0 :(得分:1)
您需要if
和else
out <- lapply(lst, function(x) {
if (length(x) <= 4) {
scale(x)
} else {
fit <- lm(x ~ poly(
x = 1:length(x),
degree = 5,
raw = TRUE
))
return(resid(fit) - mean(resid(fit)) / sd(resid(fit)))
}
})
out
#$a
# 1 2 3 4 5 6 7 8 9
# 12.047467 -1.783343 -14.687917 -12.902068 -8.652886 -4.053071 30.404730 3.453593 39.257979
# 10 11 12 13 14 15 16 17 18
# -1.380593 -7.817887 -15.061277 -19.464085 -32.319915 -40.256981 -20.832448 146.873239 -49.437978
# 19 20 21 22 23 24
# 58.823894 -37.457437 -26.198873 -12.712270 1.201236 12.956892
#$b
# [,1]
#[1,] 0.9671130
#[2,] -0.4517055
#[3,] -1.1871746
#[4,] 0.6717671
#attr(,"scaled:center")
#[1] 130.7
#attr(,"scaled:scale")
#[1] 17.26789