5

假设我有这些数据,

(df <- data.frame( col1 = c('My','Your','His','Thir'), col2 = c('Cat','Dog','Fish','Dog')))

  col1 col2
1   My  Cat
2 Your  Dog
3  His Fish
4 Thir  Dog

我想像这样组合列

`some magic`

  col1 col2      col3
1   My  Cat    My Cat
2 Your  Dog  Your Dog
3  His Fish  His Fish
4 Thir  Dog  Thir Dog

我该怎么办?甚至可能像这样使用逗号(,),

`some magic`

  col1 col2      col3
1   My  Cat    My, Cat
2 Your  Dog  Your, Dog
3  His Fish  His, Fish
4 Thir  Dog  Thir, Dog
4

2 回答 2

9

df$col3 <- paste(df$col1, df$col2, sep=","). 您还可以使用sprintfpaste0功能。

df$col3 <- paste(df$col1, df$col2, sep=",") # comma separator
df$col3 <- paste0(df$col1, df$col2) # for no separator
于 2012-11-28T01:15:40.160 回答
2

如果您想将它们保留为两者的列表,(而不是连接两者的字符串),那么以下将很好用

within(df, col3 <- Map(list, as.character(col1),as.character(col2)))  

  col1 col2      col3
1   My  Cat   My, Cat
2 Your  Dog Your, Dog
3  His Fish His, Fish
4 Thir  Dog Thir, Dog

Map是一个简单的包装器mapply(..., SIMPLIFY = FALSE)

于 2012-11-28T01:29:16.327 回答