0

我喜欢将 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=""))

当然,这仅提供了一个带有“coloryeartype”条目的列,与dat$tot1. 你会怎么做?do.call(paste, list(get(cnames),collapse=""))报告错误Error in get(cnames) : object 'color' not found

谢谢克里斯托夫

4

2 回答 2

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=","))
于 2014-12-07T10:44:34.990 回答
0

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" 
于 2014-12-07T17:31:15.243 回答