[R] how to assign a value to a specific position of a list
MacQueen, Don
macqueen1 at llnl.gov
Mon May 1 18:35:12 CEST 2017
It's not clear what you're trying to do. However, to "assign a value to a specific position of a list", this example should show you how.
lst <- vector('list', 10) ## see the help page for list
names(lst) <- paste0('list.',1:10)
## to assign 'a' to position 3:
pos <- 3
lst[[pos]] <- 'a'
I completely agree with Jeff Newmiller's recommendation to avoid using assign. It's probably the wrong tool for what you're trying to do (whatever that is).
(and note that I have borrowed Jeff's name "lst" for the list with 10 elements [not variables] whose names are "list_1" "list_2" etc.)
(and I refuse to use "_" in R object names, but that's a personal preference)
-Don
--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
On 4/30/17, 8:17 AM, "R-help on behalf of Jinsong Zhao" <r-help-bounces at r-project.org on behalf of 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.
More information about the R-help
mailing list