[R] using variable from for loop in naming new variables
Joshua Wiley
jwiley.psych at gmail.com
Thu Sep 16 22:23:31 CEST 2010
Dear Jim,
Just to follow up some of the great suggestions with some examples:
#########################################
# Initialize a list, length 4
lstuff <- vector(mode = "list", length = 4)
# store the results of your for loop in it
for (i in 1:4) {
lstuff[[i]] <- 3 + i
}
# The assign() way
for(i in 1:4) {
assign(x = paste("stuff", i, sep = ''),
value = 3 + i, envir = .GlobalEnv)
}
# Now lets see about accessing the data
stuff1
lstuff[[1]]
lstuff # see all elements of the list at once
# So far, so good, but since they are named similarly
# maybe I want to do a similar operation on all of them
# Using the list
lstuff <- lapply(lstuff, '+', y = 3)
# Using the results of the for loop
# stuff1 <- stuff1 + 3
# for every single one, or...
for(i in 1:4) {
assign(x = paste("stuff", i, sep = ''),
value = get(paste("stuff", i, sep ='')) + 3,
envir = .GlobalEnv)
}
# looking again
stuff1
lstuff[[1]]
# if you are concerned because the real thing is more complex
lstuff[[1]] <- data.frame(A = 1:10, B = 11:20)
lstuff[[2]] <- matrix(rnorm(10))
# you can store much more complex objects in the list
# so no need to worry if "stuff" is actually going to be
# data frames or tables or ...
################################################
Cheers,
Josh
On Thu, Sep 16, 2010 at 8:44 AM, Maas James Dr (MED) <J.Maas at uea.ac.uk> wrote:
> Simple one here ... but can't get it to work ...
>
> for (i in 1:4){
> paste("stuff",[i]),sep="") <- 3 + i
> }
>
> ls()
> rm(list=ls())
>
>
>
> I just want it to create 4 new variables called stuff1, stuff2, stuff3, stuff4 with the corresponding assignments. I realise that there are more elegant functions but this is just a model of a bigger situation.
>
> Thanks
>
> Jim
>
>
> ===============================
> Dr. Jim Maas
> University of East Anglia
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list