[R] errors when trying to rename data frame columns

Gabor Grothendieck ggrothendieck at myway.com
Mon Dec 13 04:55:43 CET 2004


bogdan romocea <br44114 <at> yahoo.com> writes:

: 
: Dear R users,
: 
: I need to rename the columns of a series of data frames. The names of
: the data frames and those of the columns need to be pulled from some
: vectors. I tried a couple of things but only got errors. What am I
: missing?
: 
: #---create data frame
: dframes <- c("a","b","c")
: assign(dframes[2],data.frame(11:20,21:30))
: 
: #---rename the columns
: cols <- c("one","two")
: 

   df <- data.frame(11:20, 21:30)
   names(df) <- cols
   assign(dframes[2], df)

At the expense of some complexity you can do it all in one 
assign like this:

   assign(dframes[2], as.data.frame(
            mapply("{", cols, list(11:20, 21:30), SIMPLIFY = FALSE)  
   ))

Another possibility is to paste together, as a character string,
the names<- statement and then parse and eval it:

   assign(dframes[2], data.frame(11:20, 21:30))
   eval(parse(text = paste("names(", ") <- cols", sep = dframes[2])))


: > names(get(dframes[2])) <- cols
: Error: couldn't find function "get<-"
: > assign(dframes[2],data.frame(cols[1]=11:20,cols[2]=21:30))
: Error: syntax error
: > labels(get(dframes[2]))[[2]] <- cols
: Error: couldn't find function "labels<-"
: 
: I'm using R 2.0.0 on Windows XP.




More information about the R-help mailing list