[R] how to assign a value to a specific position of a list

Jinsong Zhao jszhao at yeah.net
Tue May 2 02:37:00 CEST 2017


Thank you very much, and your reply is helpful.

I don't like assign, and even don't use parse in my previous codes. 
However, in the case I encountered, assign and parse may be the right 
tools. Here is the code I used:

# in the workspace, there are tens directory.
# In each directory, there are lots of *.ASC file,
# with second column is the data.
# Each *.ASC file has a name with pattern i-tr-??.ASC.
# i is the directory name, tr is a group name, and ?? are the index.
# I have to collect all tr-?? into a matrix,
# and put all i-tr-?? into a list EEM_i.

for (i in dir()) {
    assign(paste("EEM_",i,sep=""), list())
    fn <- list.files(path = i, pattern = "ASC")
    tr <- sort(as.numeric(unique(unlist(lapply(strsplit(fn, "-"),"[[", 
2)))))
    for (j in 1:length(tr)) {
       fn_tr <- list.files(path = i, pattern = paste(i, tr[j], "...ASC", 
sep="-"))
       EEM_tmp <- matrix(NA,ncol = length(fn_tr),nrow = 371)
       for (k in 1:length(fn_tr)) {
          data_tmp <- read.csv(paste(i,fn_tr[k],sep="/"), header = FALSE)
          if (dim(data_tmp)[1] != 371) next
          EEM_tmp[,k] <- data_tmp[,2]
       }
       eval(parse(text=paste("EEM_",i,"[[",j,"]]<-","EEM_tmp", sep="")))
    }
}

Any alternatives or improvements? Thanks a lot.

Best,
Jinsong

On 2017/4/30 23:48, peter dalgaard wrote:
> assign(paste("list_", i, "[[1]]", sep = ""), 5) creates a new variable with a funny name.
>
> You'd have to parse() and eval() to make that work, something like
>
> eval(parse(text=paste("list_",i,"[[1]]<-",5, sep="")))
>
> However,
> -------
>> fortunes::fortune("parse")
>
> If the answer is parse() you should usually rethink the question.
>    -- Thomas Lumley
>       R-help (February 2005)
> -------
>
> It is much easier to handle this using a data structure containing a list of lists:
>
> l <- rep(list(list()), 10)
> for ( i in 1:10 )
>    l[[i]][[1]] <- 5
>
>> On 30 Apr 2017, at 17:17 , Jinsong Zhao <jszhao at yeah.net> wrote:
>>
>> Hi there,
>>
>> I have a problem with assign(). Here is the demo code:
>>
>> for (i in 1:10) {
>>   # create a list with variable name as list_1, list_2, ..., etc.
>>   assign(paste("list_", i, sep = ""), list())
>>   # I hope to assign 5 to list_?[[1]], but I don't know how to code it.
>>   # list_1[[1]] <- 5 # works, however
>>   assign(paste("list_", i, "[[1]]", sep = "", 5) # does not work
>> }
>>
>> How to do? Is there any alternatives? Many thanks!
>>
>> Best,
>> Jinsong
>>



More information about the R-help mailing list