2

假设有 2 个 data.frames,例如:

dat1 <- read.table("[path_dat1]", header=TRUE, sep=",")
    id   name  age
     1   Jack   21
     2  James   40

dat2 <- read.table("[path_dat2]", header=TRUE, sep=",")
    id      interests
     1       football
     1     basketball
     1         soccer
     2  pingpang ball

如何将表 1 和表 2 加入到如下所示的 data.frame 中?

  id   name age                       interests
1  1   Jack  21  (football, basketball, soccer)
2  2  James  40                 (pingpang ball)

如何以最简单的方式使用 plyr 加入这些?

4

2 回答 2

3

我不能告诉你如何在 plyr 中解决这个问题,但可以在 base 中:

dat3 <- aggregate(interests~id, dat2, paste, collapse=",")
merge(dat1, dat3, "id")

编辑:如果你真的想要括号,你可以使用:

ppaste <- function(x) paste0("(", gsub("^\\s+|\\s+$", "", paste(x, collapse = ",")), ")")
dat3 <- aggregate(interests~id, dat2, ppaste)
merge(dat1, dat3, "id")
于 2012-12-10T05:35:53.923 回答
1

使用泰勒的例子:

dat1$interests <- ave(dat1$id, dat1$id, 
        FUN=function(x) paste(dat2[ dat2$id %in% x, "interests"], collapse=",") )
> dat1
  id   name age                     interests
1  1   Jack  21  football, basketball, soccer
2  2  James  40                 pingpang ball
于 2012-12-10T07:09:00.683 回答