我有一个数据框,例如
df1 <- data.frame(
A = c("USA","USA","UK","UK","France"),
B = c("Boston","New York","Cambridge","Oxford","Paris")
)
我想最终得到一个新的数据框:
df2 <- data.frame(
A = c("USA","UK","France"),
B = c("Boston; New York","Cambridge; Oxford","Paris")
)
如何使用paste()
作为&#34;汇总&#34;来汇总A?功能,还是等同于此的东西?提前感谢您提供的任何帮助。
答案 0 :(得分:1)
我会使用data.table
:
library(data.table)
##
R> (df2 <- data.table(df1)[
,.(B = paste0(B, collapse = "; ")),
by = "A"])
# A B
#1: USA Boston; New York
#2: UK Cambridge; Oxford
#3: France Paris
如果您坚持要求data.frame
获得结果,请在之后使用setDF(df2)
。