作者myfirstjump (我的第一跳)
看板R_Language
标题[问题] 呼叫list中的lm model
时间Thu Feb 1 20:40:49 2018
[问题类型]:
程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
[软体熟悉度]:
入门(写过其他程式,只是对语法不熟悉)
[问题叙述]:
建立多个lm模型,用loop存入一个list,给 $reg1, $reg2, ...等名字
建立多个变数,用loop存取这些lm的coefficient[[2]],就是想存斜率
如下code,卡在呼叫lm的coefficient的地方,呼叫line[i]是okay的。
呼叫coefficient後,会return NULL。
[程式范例]:
https://ideone.com/LfFEzU
test <- function() {
vec1 <- c(1,2,3)
vec2 <- c(4,5,6)
line <- list()
for (i in 1:2) {
line$i <- lm(vec2 ~ vec1)
names(line)[i] <- paste0("reg", i)
}
# return(line)
coef <- list()
for (i in 1:2) {
coef$i <- line[i]$coefficient[[1]]
return(coef$i) # <---------------- 卡在这个输出
names(coef)[i] <- paste0("coe", i)
}
return(coef)
}
test()
[环境叙述]:
> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=Chinese (Traditional)_Taiwan.950 LC_CTYPE=Chinese
(Traditional)_Taiwan.950
[3] LC_MONETARY=Chinese (Traditional)_Taiwan.950 LC_NUMERIC=C
[5] LC_TIME=Chinese (Traditional)_Taiwan.950
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.7.4 readxl_1.0.0 data.table_1.10.4-3 xlsx_0.5.7
[5] xlsxjars_0.6.1 rJava_0.9-9 limma_3.34.6
loaded via a namespace (and not attached):
[1] Rcpp_0.12.15 assertthat_0.2.0 cellranger_1.1.0 R6_2.2.2
magrittr_1.5
[6] pillar_1.1.0 rlang_0.1.6 bindrcpp_0.2 tools_3.4.3
glue_1.2.0
[11] compiler_3.4.3 pkgconfig_2.0.1 bindr_0.1 tibble_1.4.2
[关键字]:
for loop, lm, coefficient
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 59.124.164.132
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1517488860.A.932.html
※ 编辑: myfirstjump (36.226.183.235), 02/01/2018 21:05:13
1F:→ myfirstjump: 存取coef应该用vector就好,不过问题还在 02/01 21:08
已经由某大大站内信告诉我问题
list取值部分要用[[]]取代[]
订正一下我的code:
原来 coef$i <- line[i]$coefficient[[1]]
改为 coef$i <- line[[i]]$coefficient[[1]]
感谢板友协助!
※ 编辑: myfirstjump (36.226.183.235), 02/01/2018 22:08:25