我想将lm()应用于按主题分组的观察结果,但无法计算出sapply语法。最后,我想要一个数据帧,每个主题有1行,并具有截距和斜率(即,以下行:subj,lm $ coefficients [1] lm $ coefficients [2])
set.seed(1)
subj <- rep(c("a","b","c"), 4) # 4 observations each on 3 experimental subjects
ind <- rnorm(12) #12 random numbers, the independent variable, the x axis
dep <- rnorm(12) + .5 #12 random numbers, the dependent variable, the y axis
df <- data.frame(subj=subj, ind=ind, dep=dep)
s <- (split(df,subj)) # create a list of observations by subject
Run Code Online (Sandbox Code Playgroud)
我可以从s中获取一组观察值,制作一个数据框,然后得到我想要的:
df2 <- as.data.frame(s[1])
df2
lm1 <- lm(df2$a.dep ~ df2$a.ind)
lm1$coefficients[1]
lm1$coefficients[2]
Run Code Online (Sandbox Code Playgroud)
我在遍历s的所有元素并将数据转换成我想要的最终形式时遇到麻烦:
lm.list <- sapply(s, FUN= …Run Code Online (Sandbox Code Playgroud)