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

时间:2023-02-07 23:47:46

I have this data frame called df:

我有这个名为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))

The percent column is the percentage increase compared to the previous row.

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

I need to find out the pair of rows where percent is less than 10%.

我需要找出百分比小于10%的行对。

The desired output would be: id 8 and id 9 (basically its resulted id and -1)

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

2 个解决方案

#1


2  

You can do this.

你可以这样做。

Divide previous diff by current value and find fraction (percentage):

将先前差异除以当前值并找到分数(百分比):

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

Check if fraction difference is less than 0.1 (10%)

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

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

Find ID's in your data:

在您的数据中查找ID:

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

Data:

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")

#2


0  

You can use which() to find the elements in df$percent that are smaller than 0.1 and also larger than 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

If you don't want the row numbers, but you want the opty_id instead, use:

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

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

#1


2  

You can do this.

你可以这样做。

Divide previous diff by current value and find fraction (percentage):

将先前差异除以当前值并找到分数(百分比):

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

Check if fraction difference is less than 0.1 (10%)

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

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

Find ID's in your data:

在您的数据中查找ID:

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

Data:

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")

#2


0  

You can use which() to find the elements in df$percent that are smaller than 0.1 and also larger than 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

If you don't want the row numbers, but you want the opty_id instead, use:

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

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