【问题标题】:R - "$ operator is invalid for atomic vectors" error messageR - “$ 运算符对原子向量无效”错误消息
【发布时间】:2018-03-14 16:20:09
【问题描述】:

我收到此错误:

$ 运算符对原子向量无效

当我运行这个脚本时:

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$ctfm_list[[ct]],但我得到了同样的错误。

此外,摘要不会打印出来。我不知道为什么它不起作用。

【问题讨论】:

  • 我想你想要fm_list[[fn]] &lt;- cur_fm,如果你想在for循环的每次迭代中附加列表。
  • 我刚刚尝试了这两种方法,但仍然出现错误。
  • 我不知道这是否重要,但我使用的是 RStudio Windows 1.1.423 和 R 3.4.3 x86_64。
  • 我认为它发生在这一行:fm_list$ct
  • 我可以重现您的问题。 summary 是隐藏的,如果我使用 fm_list[[ct]] &lt;- cur_fm,错误消息是由最后 (!) 行 (multiplot) 引起的

标签: r lm


【解决方案1】:

您的代码存在三个问题:

  1. 将函数返回值存储在列表中

  2. 调用multiplot 函数的方式错误(没有plotlist 参数 - 请参阅?multiplot

  3. 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)

请注意,该解决方案存在一些错误风险,例如。 G。如果您的文件名与 multiplot 函数的形式参数的名称相同。

您可以通过 e 来避免这种风险。 G。添加不属于任何参数名称的前缀:

fm_list[[paste0("dot_dot_dot_", fn)]] <- cur_fm

【讨论】:

  • Ohmygosh,你真是太棒了!
猜你喜欢
  • 1970-01-01
  • 2018-08-23
  • 2015-10-02
  • 1970-01-01
  • 2021-08-20
  • 2020-06-21
  • 2021-11-07
  • 1970-01-01
相关资源
最近更新 更多