[R] how to assign a value to a specific position of a list
peter dalgaard
pdalgd at gmail.com
Sun Apr 30 17:48:02 CEST 2017
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
>
> ______________________________________________
> 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.
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list