Skip to content

Assigning colnames in loop

2 messages · Peter Jepsen, Sundar Dorai-Raj

#
Dear R-listers,

I am trying to assign colnames to a data frame within a loop, but I keep
getting a "target of assignment expands to non-language object"-error. I
need to split up a large dataset into about 20 smaller ones, and I would
like to assign colnames within the loop, so I won't have to type the
same thing 20 times over.

I have concocted this really goofy example which constructs two
datasets:

-----
male <- rep(0:1, each=5)
age <- factor(c(10:14,10:14))
DF <- data.frame(male, age, res1=rnorm(10), res2=rnorm(10),
res3=rnorm(10))

for(n in 0:1) {
	assign(paste("test",n, sep="."), as.data.frame(t(subset(DF,
male==n, select=c(res1, res2, res3)))))
	colnames(get(paste("test",n, sep="."))) <-
paste("age",levels(age), "m", n, sep="") # This line gives an error.
	assign(colnames(paste("test",n, sep="."))) <-
paste("age",levels(age), "m", n, sep="") # This line gives the same
error.
}
-------
The following command assigns the right colnames to the 'test.0' data
frame, but I want this line inside the loop so I won't have to type it
20 times over. 
colnames(test.0) <- paste("age",levels(age), "m", 0, sep="") 


Thank you in advance for any assistance.
Peter.
R version 2.8.1 (2008-12-22) 
i386-pc-mingw32 

locale:
LC_COLLATE=Danish_Denmark.1252;LC_CTYPE=Danish_Denmark.1252;LC_MONETARY=
Danish_Denmark.1252;LC_NUMERIC=C;LC_TIME=Danish_Denmark.1252

attached base packages:
[1] tools     stats     graphics  grDevices utils     datasets  methods
base     

other attached packages:
[1] epiR_0.9-14     maptools_0.7-18 sp_0.9-29       foreign_0.8-30
chron_2.3-28   

loaded via a namespace (and not attached):
[1] grid_2.8.1      lattice_0.17-20
#
It's always best to do this with list operations (e.g. lapply) rather
than a loop:

DF1 <- split(DF, DF$male)
DF2 <- lapply(DF1, function(x) {
  x2 <- t(as.matrix(x[3:5], dimnames = list(levels(x$age), NULL)))
  as.data.frame(x2)
})

Then DF2[["0"]] and DF2[["1"]] are the data.frames you want.

HTH,

--sundar
On Mon, Feb 2, 2009 at 2:30 PM, Peter Jepsen <PJ at dce.au.dk> wrote: