比较data.frame中具有相同ID的值对,并为每行返回布尔值

时间:2015-03-11 19:50:33

标签: r

我有一个带有公共ID的值对的data.frame。我只想根据每一行的值是否大于其配对值来判断为TRUE / FALSE。

这是数据:

d<-structure(list(id = c(400585859L, 400585859L, 400585862L, 400585862L,400585863L, 400585863L, 400585867L, 400585867L, 400585868L, 400585868L), pts = c(69L, 70L, 77L, 70L, 76L, 69L, 89L, 76L, 73L, 75L)), .Names = c("id","pts"), row.names = c(NA, -10L), class = "data.frame")

如果我使用ddply,我最终只有5行而不是10行:

ddply(d, .(id), summarize, pts[1] > pts[2])

如果我的数据如下:

      id pts
  400585859  69
  400585859  70
  400585862  77
  400585862  70
  400585863  76
  400585863  69
  400585867  89
  400585867  76
  400585868  73
  400585868  75

我想:

     id pts
      400585859  69 FALSE
      400585859  70 TRUE
      400585862  77 TRUE
      400585862  70 FALSE
      400585863  76 TRUE
      400585863  69 FALSE
      400585867  89 TRUE
      400585867  76 FALSE
      400585868  73 FALSE
      400585868  75 TRUE

2 个答案:

答案 0 :(得分:2)

这是一个解决方案

ddply(d, .(id), transform, status = pts > min(pts))

答案 1 :(得分:2)

这是一个使用dplyr

的人
library(dplyr)
d %>% group_by(id) %>% mutate(status = pts > min(pts))