如何将单行中的两个数字范围与同一行中的数字进行比较?
How to compare a range of two numbers in a single row with a number in the same row?
我有三列,一列是产品的最低价,一列是产品的最高价,还有一列是产品的实际价格。我试图逐行将最低和最高价格与实际价格进行比较,看它是否在该范围内。
这是一些示例数据:
MinimumPrice MaximumPrice ActualPrice
30.5 41 51
95.5 100 92
45.5 50 43
70 75 80
我尝试使用:
TBAcomparison$withinRange_Price<- ifelse(sapply(Prices$ActualPrice, function(p)
any(Prices$MaximumPrice <= p & Prices$MinimumPrice>= p)),1, NA)
不过,这并不是我要找的。
结果应该是:
MinimumPrice MaximumPrice ActualPrice WithinRange
30.5 41 51 1
95.5 100 92 NA
42.5 50 43 1
70 75 80 NA
如能提供帮助,我们将不胜感激。
输入:
structure(list(MinimumPrice = c(30.5, 95.5, 45.5, 70), MaximumPrice = c(41,
100, 50, 75), ActualPrice = c(51, 92, 43, 80), withinrange = c("No",
"No", "No", "No")), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
<
和 >
是矢量化的,因此使用 sapply
会使您过于复杂。试试这个:
Prices$withinRange_Price <- with(Prices, ifelse(MinimumPrice <= AcutalPrice & ActualPrice <= MaximumPrice, 1, NA))
我有点困惑,您的代码似乎使用了 2 个数据框,但您的文本和示例数据仅指示 1 个数据框,但我会把它留给您。
选项dplyr
library(dplyr)
Prices %>%
mutate(withinRange_Price = case_when(ActualPrice > MinimumPrice &
ActualPrice <= MaximumPrice ~ 1))
我有三列,一列是产品的最低价,一列是产品的最高价,还有一列是产品的实际价格。我试图逐行将最低和最高价格与实际价格进行比较,看它是否在该范围内。
这是一些示例数据:
MinimumPrice MaximumPrice ActualPrice
30.5 41 51
95.5 100 92
45.5 50 43
70 75 80
我尝试使用:
TBAcomparison$withinRange_Price<- ifelse(sapply(Prices$ActualPrice, function(p)
any(Prices$MaximumPrice <= p & Prices$MinimumPrice>= p)),1, NA)
不过,这并不是我要找的。
结果应该是:
MinimumPrice MaximumPrice ActualPrice WithinRange
30.5 41 51 1
95.5 100 92 NA
42.5 50 43 1
70 75 80 NA
如能提供帮助,我们将不胜感激。
输入:
structure(list(MinimumPrice = c(30.5, 95.5, 45.5, 70), MaximumPrice = c(41,
100, 50, 75), ActualPrice = c(51, 92, 43, 80), withinrange = c("No",
"No", "No", "No")), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
<
和 >
是矢量化的,因此使用 sapply
会使您过于复杂。试试这个:
Prices$withinRange_Price <- with(Prices, ifelse(MinimumPrice <= AcutalPrice & ActualPrice <= MaximumPrice, 1, NA))
我有点困惑,您的代码似乎使用了 2 个数据框,但您的文本和示例数据仅指示 1 个数据框,但我会把它留给您。
选项dplyr
library(dplyr)
Prices %>%
mutate(withinRange_Price = case_when(ActualPrice > MinimumPrice &
ActualPrice <= MaximumPrice ~ 1))