combine data.frame columns to new columns by vector of names

145 views Asked by At

I like to combine some columns of a data.frame to a new column, like

dat <- data.frame(
  color = sample(c("r","y","b"), 10, replace = TRUE), 
  year = sample(2011:2014, 10, replace = TRUE),
  type = sample(c("early","mid","late"), 10, replace = TRUE))

dat$tot1 <- paste(dat$color, dat$year, dat$type)

that works, but how I do it on the basis of column names?

cnames <- c("color","year","type")

dat$tot2 <- do.call(paste, list(cnames,collapse=""))

of course, this only provides a column with "coloryeartype" entries and not the same as dat$tot1. How would you do it? do.call(paste, list(get(cnames),collapse="")) reports the error Error in get(cnames) : object 'color' not found

thx Christof

2

There are 2 answers

0
akrun On BEST ANSWER

Just use

 do.call(paste, dat[cnames])
#[1] "y 2011 mid"   "r 2012 mid"   "r 2013 late"  "r 2014 mid"   "r 2011 late" 
#[6] "b 2012 early" "y 2014 early" "r 2013 mid"   "r 2011 late"  "b 2014 early"

If you need different delimiter

 do.call(paste, c(dat[cnames], sep=","))
0
Selva On

Here is another way -

apply(dat[cnames], 1, function(x){paste(x, collapse=" ")})
#  [1] "b 2011 early" "r 2014 mid"   "y 2012 early" "y 2013 late"  "y 2011 late" 
   [6] "y 2014 late"  "b 2011 mid"   "b 2011 early" "b 2011 mid"   "y 2013 late"