Return rows establishing a “closest value to” in R

后端 未结 1 1685
醉酒成梦
醉酒成梦 2020-12-18 08:00

I have a data frame with different IDs and I want to make a subgroup in which: for each ID I will only obtain one row with the closest value to 0.5 in variable Y.

Th

相关标签:
1条回答
  • 2020-12-18 08:56

    You need to calculate the difference from 0.5 and then keep the smallest one. One way to do this would be as so:

    ddply(df, .(ID), function(z) {
      z[abs(z$Y - 0.50) == min(abs(z$Y - 0.50)), ]
    })
    

    Note that the way I've coded it above, omitting your [1, ], if two rows are exactly tied both will be kept.

    It should be fine since we're doing the exact same calculation on either side of ==, but I often worry about numerical precision problems, so we could instead use which.min. Note that which.min will return the first minimum in the case of a tie.

    ddply(df, .(ID), function(z) {
      z[which.min(abs(z$Y - 0.50)), ]
    })
    

    Another robust way to do it would be to order the data frame by difference from 0.5 and keep the first row per ID. At this point I'll transition over to dplyr, though of course you could use dplyr or plyr::ddply for any of these methods.

    library(dplyr)
    df %>% group_by(ID) %>%
      arrange(abs(Y - 0.5)) %>%
      slice(1)
    

    I'm not sure how arrange handles ties. For more methods see Get rows with minimum of variable, but only first row if multiple minima, and just always use abs(Y - 0.5) as the variable you are minimizing.

    0 讨论(0)
提交回复
热议问题