【问题标题】:Compare pairs of values with same ID in a data.frame and return boolean for each row比较 data.frame 中具有相同 ID 的值对并为每一行返回布尔值
【发布时间】:2015-03-11 19:50:33
【问题描述】:

我有一个由具有共同 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

【问题讨论】:

  • 根据您的回答,这就是我认为您想要的ddply(d, .(id), transform, status = pts &gt; min(pts))
  • 是的!谢谢!我将其添加为答案。

标签: r


【解决方案1】:

这是一种解决方案

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

【讨论】:

    【解决方案2】:

    这是一个使用dplyr的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2014-04-30
      • 2022-01-18
      • 2019-03-29
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多