[問題] 呼叫list中的lm model (已解決)
[問題類型]:
程式諮詢(我想用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://www.ptt.cc/bbs/R_Language/M.1517488860.A.932.html
※ 編輯: myfirstjump (36.226.183.235), 02/01/2018 21:05:13
→
02/01 21:08,
7年前
, 1F
02/01 21:08, 1F
已經由某大大站內信告訴我問題
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
R_Language 近期熱門文章
PTT數位生活區 即時熱門文章
58
130