通过名称向量将data.frame列组合到新列

时间:2014-12-07 10:37:38

标签: r dataframe paste do.call

我喜欢将data.frame的某些列组合到一个新列,例如

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)

有效,但我是如何根据列名进行的?

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

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

当然,这只提供了一个&#34; coloryeartype&#34;条目与dat$tot1不同。你会怎么做? do.call(paste, list(get(cnames),collapse=""))报告错误Error in get(cnames) : object 'color' not found

THX 克里斯托夫

2 个答案:

答案 0 :(得分:1)

只需使用

 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"

如果您需要different分隔符

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

答案 1 :(得分:0)

这是另一种方式 -

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"