在数据帧的一个单元格中返回多个匹配值

时间:2015-10-15 18:20:41

标签: r dataframe

R中是否有任何函数将数据帧中的值与另一个值进行比较,并在数据帧的单个单元格中返回多个匹配值? match()(类似于EXCEL中的vlookup())返回第一个匹配值。以下是我尝试使用dt1并获取dt2

的示例
    animal <- c("Dog","Dog","Duck","Duck","Duck","Mouse","Mouse","Pig","Pig","Pig")
    name <- c("Tim","Brown","Jack","Harry","Jack","Tom","Sal","Jack","Tim","Don")
    age <- c(4,6,2,3,6,1,2,2,3,3)
    dt1 <- data.frame(animal,name,age)

我想生成一个类似于数据框的新数据框dt2,如下所示:

    animal <- c("Dog","Duck","Mouse", "Pig")
    NumberofUniqueNames <- c(2,2,2,3)
    Names <- c("Tim, Brown", "Jack, Harry", "Tom, Sal", "Jack, Tim, Don")
    dt2 <- data.frame(animal,NumberofUniqueNames,Names)

example

我搜索了SO和谷歌,发现了类似于EXCEL的东西,但没有任何关于R的东西。

EXCEL的一些示例包括herehere

1 个答案:

答案 0 :(得分:1)

library(plyr)
animal <- c("Dog","Dog","Duck","Duck","Duck","Mouse","Mouse","Pig","Pig","Pig")
name <- c("Tim","Brown","Jack","Harry","Jack","Tom","Sal","Jack","Tim","Don")
age <- c(4,6,2,3,6,1,2,2,3,3)
dt1 <- as.data.frame(cbind(animal,name,age))
View(dt1)

dt2 = ddply(dt1, .(animal), summarise, length(unique(name)), paste(unique(name), collapse = ", "))
View(dt2)

> dt2
  animal ..1            ..2
1    Dog   2     Tim, Brown
2   Duck   2    Jack, Harry
3  Mouse   2       Tom, Sal
4    Pig   3 Jack, Tim, Don