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

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sun Apr 30 17:56:48 CEST 2017


My reaction is... why do you think this is a good approach to pursue?

Avoid using assign!

library( fortunes )
fortune( 236 )

If you really need another level of containment, put your multiple lists into another list:

lst  <- lapply( 1:10, list )
lst[[1]][[1]] <- 5

-- 
Sent from my phone. Please excuse my brevity.

On April 30, 2017 8:20:17 AM PDT, Jinsong Zhao <jszhao at yeah.net> wrote:
>On 2017/4/30 23:17, Jinsong Zhao 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
>      # wrong code in previous message, the correct on should be:
>     assign(paste("list_", i, "[[1]]", sep = ""), 5) # does not work...
>> }
>>
>> How to do? Is there any alternatives? Many thanks!
>>
>> Best,
>> Jinsong
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list