This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Variable definition in R

Hi everyone.

I have the following line of code where R rejects the expression on the left to be treated as an assignee variable.

for (i in 1:length(my_list)){
paste(eval(parse(text='names(my_list[i])')),"table",sep="") <- read.table(paste("./foo/",paste(eval(parse(text='names(my_list[i])')),".csv",sep=""),sep=""))
}

Any comments you would like to make here.

Thanks. SJ.

Edit:

Just to add, the exception reported is:

Error in paste(eval(parse(text = "names(my_list[i])")), "table", sep = "") <- read.table(paste("./foo/",  : 
  target of assignment expands to non-language object
r

Hello Shaurya Jauhari!

We believe that this post does not fit the main topic of this site.

Not a bioinformatics question.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

2 answers

There are better ways to read multiple CSVs into R, for example:

allCSVs <- lapply(my_list, function(i){
  read.table(paste0("./foo/", i, ".csv"))
  })

See this SO post for more options.

What you are trying to do is not wrong but not advised.

  • avoid using forloop, use lapply
  • avoid cluttering workspace with multiple dataframes with similar structure, keep them in a list instead.
  • avoid using "eval parse", because: ...

If the answer is parse() you should usually rethink the question. - Thomas Lumley R-help (February 2005)

Thanks zx8754. Few things here though:

  1. I completely dig that lapply() usage shall be a viable alternative, and it works; just that the same error is engendered.
  2. The question here is not just to read a file, rather also to save it as a R data object for further manipulation.
  3. The variable (to which a file is to be referenced) naming has to be such that it retains the nomenclature of the list items, in addition to the term "table" flanked to the right side of it.

Just for the record, the expressions on the left and right sides of the assignment operator are functioning perfectly, individually. What's perplexing is that why can't the variable naming and assignment co-function in an iteration.

Any advise now?

lapply already returns a named list and it is saved as an R list "allCSVs". We can get individual dataframe from the list by name, something like: allCSVs$myName, assuming "myName" is one of the items in the my_list.

And regarding the error, see this post at SO, basically you are trying to assign a variable to a name which is not valid.

Just to add, the exception reported is:

Error in paste(eval(parse(text = "names(my_list[i])")), "table", sep = "") <- read.table(paste("./foo/", : target of assignment expands to non-language object

Log in to answer this question.