根据条件从列中选择多个值

时间:2018-02-06 12:20:47

标签: r

我有一个名为df的数据框:

df <- structure(list(opty_id = c(123L, 147L, 165L, 198L, 203L, 209L, 219L, 271L, 284L), 
               amount_opty = c(855252.21, 590259.86, 742818.76, 742818.76, 211760, 149190.3, 118924.22, 414663.687, 403313.319 ), 
               percent = c(NA, 0.309841175, NA, 0, 0.714923732, 0.295474594, 0.202868953, NA, 0.027372467)), 
               .Names = c("opty_id", "amount_opty", "percent"), 
               class = "data.frame", row.names = c(NA, -9L))

percent列是与前一行相比的百分比增长。

我需要找出percent小于10%的行对。

所需的输出为: id 8和id 9 (基本上是结果id和-1)

2 个答案:

答案 0 :(得分:2)

你可以这样做。

将之前的diff除以当前value并找到分数(百分比):

c(df$diff[-1], NA) / df$value
# [1] 0.3333333 0.0000000 0.0400000 0.1666667        NA

检查分数差异是否小于0.1(10%)

c(df$diff[-1], NA) / df$value < 0.1
# [1] FALSE  TRUE  TRUE FALSE    NA

在您的数据中查找ID:

which(c(df$diff[-1], NA) / df$value < 0.1) + 1
# [1] 3 4

数据:

df <- structure(list(id = 1:5, value = c(60L, 40L, 50L, 48L, 40L), 
diff = c(0L, 20L, 0L, 2L, 8L)), .Names = c("id", "value", "diff"), row.names = c(NA, -5L), class = "data.frame")

答案 1 :(得分:0)

您可以使用which()查找df$percent中小于0.1 也大于0的元素:

main_id <- which(df$percent < 0.1 & df$percent > 0.0)   # gives 9
target  <- c(main_id - 1, main_id)
target
# [1] 8 9

如果您不想要行号,但想要opty_id,请使用:

df$opty_id[target]
# [1] 271 284