简体   繁体   中英

R - “$ operator is invalid for atomic vectors” error message

I receive this error:

$ operator is invalid for atomic vectors

when I run this script:

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)

The script should read in 12 csv files, run an lm() on each one, attempt to store the results in a list, and then does a multiplot on the list.

I have tried fm_list$ct and fm_list[[ct]] and I get the same error.

In addition, the summary does not print out. I can't figure out why it doesn't work.

Your code had three problems:

  1. Store the function return value in a list

  2. wrong way of calling the multiplot function (there is no plotlist argument - see ?multiplot .

  3. summary is only printed to the console if it is outside of any code block (R is a scripting language). If you put it into a code block (here: for function) you have to use print

The solution is:

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

Please note that the solution has some risks of errors, eg if you have a file name that is the same as the name of a formal argument of the multiplot function.

You could avoid this risk by eg adding a prefix that is not part of any argument name:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM