简体   繁体   English

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

[英]combine data.frame columns to new columns by vector of names

I like to combine some columns of a data.frame to a new column, like 我喜欢将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)

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 . 当然,这仅提供具有“ coloryeartype”条目的列,而与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 do.call(paste, list(get(cnames),collapse=""))报告Error in get(cnames) : object 'color' not found

thx Christof 克里斯托夫

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 如果您需要different定界符

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

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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM