说我有这个数据,
(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
答案 0 :(得分:8)
df$col3 <- paste(df$col1, df$col2, sep=",")
。您还可以使用sprintf
和paste0
函数。
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
Map
是mapply(..., SIMPLIFY = FALSE)