[英]R - “$ operator is invalid for atomic vectors” error message
我收到此錯誤:
$運算符對原子向量無效
當我運行此腳本時:
require(coefplot)
filenames <- list.files(path = '/Documents/R/data/', pattern = "account_exp_10_sb_sql__[0-9]{2,3}-[0-9]{2,3}.csv", full.names = TRUE)
analyze <- function(filename){
fm_1 <- NULL
dx_1 <- NULL
cat('reading: ', filename)
dx_1 <- read.csv(filename)
head(dx_1)
fm_1 <- lm(default_perc ~ credit_score + email + credit_card_pmt, data = dx_1)
return(fm_1)
}
cur_fm <- NULL
ct <- 1
fm_list <- list()
for (fn in filenames)
{
#cat(ct, ' ', fn)
cur_fm <- analyze(fn)
summary(cur_fm)
fm_list$ct <- cur_fm
ct <- ct + 1
#stop()
}
#fm_list
multiplot(plotlist = fm_list)
該腳本應讀取12個csv文件,對每個文件運行lm()
,嘗試將結果存儲在列表中,然后在列表上進行多圖繪制。
我已經嘗試過fm_list$ct
和fm_list[[ct]]
並得到相同的錯誤。
此外,摘要不會打印出來。 我不知道為什么它不起作用。
您的代碼有三個問題:
將函數返回值存儲在列表中
調用的方式不對multiplot
功能(沒有plotlist
參數-見?multiplot
。
僅當summary
位於任何代碼塊(R是腳本語言)之外時,才會打印到控制台。 如果將其放入代碼塊(此處for
功能),則必須使用print
解決方案是:
# ... your code as above
cur_fm <- NULL
ct <- 1
fm_list <- list()
for (fn in filenames)
{
cat(ct, ' ', fn)
cur_fm <- analyze(fn)
print(summary(cur_fm)) # 3. print required inside a code block
fm_list[[fn]] <- cur_fm # 1. use the file name as list item name
ct <- ct + 1
#stop()
}
# 2. Pass all lm results in the list in "..." argument of multiplot
# do.call requires named list elements since they are used to find
# the corresponding function arguments. If there is no match
# the list element is put into the "..." argument list
do.call(multiplot, fm_list)
請注意,該解決方案存在一些出錯的風險,例如,如果您的文件名與multiplot
函數的形式參數的名稱相同。
您可以通過添加不屬於任何參數名稱的前綴來避免這種風險:
fm_list[[paste0("dot_dot_dot_", fn)]] <- cur_fm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.