组合数据框中的列

时间:2016-03-05 20:37:36

标签: r

我在数据框中有3列第一,中间和姓氏。如果我想将3列组合成1个fullname列,我该怎么办? 例如,如果我有

df$firstname <- c("Mike","Jake", "Bob")
df$middlename <- c("John", "Jay", "Peter")
df$lastname <- c("Turner", "Larson", "Simmons")

我如何获得

> df$fullname
Mike John Turner
Jake Jay Larson
Bob Peter Simmons

1 个答案:

答案 0 :(得分:2)

我们可以使用paste

df$fullname <- do.call(paste, df)

数据

df <- structure(list(firstname = structure(c(3L, 2L, 1L), 
.Label = c("Bob", 
"Jake", "Mike"), class = "factor"), middlename = structure(c(2L, 
1L, 3L), .Label = c("Jay", "John", "Peter"), class = "factor"), 
lastname = structure(c(3L, 1L, 2L), .Label = c("Larson", 
"Simmons", "Turner"), class = "factor")), .Names = c("firstname", 
"middlename", "lastname"), row.names = c(NA, -3L),
class = "data.frame")