在数据框内连接/合并两列

时间:2012-11-28 01:12:23

标签: r join merge data-management

说我有这个数据,

(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

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分: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

Mapmapply(..., SIMPLIFY = FALSE)

的简单包装器