[R] Assigning colnames in loop

Peter Jepsen PJ at DCE.AU.DK
Mon Feb 2 23:30:41 CET 2009


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.

> sessionInfo()
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




More information about the R-help mailing list