根据预定义的阈值更新列的值

  • 本文关键字:更新 阈值 预定义 r
  • 更新时间 :
  • 英文 :


>我有一个数据集如下

Name    Price
A       100
B       123
C       112
D       114
E       101
F       102

如果价格在指定为向量中指定的值的向量的 +3 或 -3 之间,我需要一种方法来更新价格列中的值。向量可以包含任意数量的元素。

Vector = c(100,111)

更新的数据框

Name    Price
A       100
B       123
C       111
D       111
E       100
F       100

如果向量是

Vector = c(104,122) 

然后需要更新的数据帧

Name    Price
A       100
B       122
C       112
D       114
E       104
F       104
df <- data.frame('Name' = LETTERS[1:6], 'Price'= c(100,123,112,114,101,102))

transform <- function(value, conditionals){
for(cond in conditionals){
if(abs(value - cond) < 4){
return(cond)
}
}
return(value)
}
sapply(df$Price, transform, c(104,122))

这应该有效。它可能可以通过 apply 在一行中完成(但我发现有时很难阅读,所以这应该更容易阅读(。

这里有一种方法

bound <- 3
upper_bound <- Vector+bound
lower_bound <- Vector-bound
vi <- Reduce("pmax", lapply(seq_along(Vector), function(i) i*(df$Price <= upper_bound[i] & df$Price >= lower_bound[i])))
# [1] 1 0 2 2 1 1
vi_na <- replace(vi, vi == 0, NA)
# [1]  1 NA  2  2  1  1
df$Price <- dplyr::mutate(df, Price = ifelse(is.na(Vector[vi_na]), Price, Vector[vi_na]))
# Name Price.Name Price.Price
# 1    A          A         100
# 2    B          B         123
# 3    C          C         111
# 4    D          D         111
# 5    E          E         100
# 6    F          F         100

数据

df <- read.table(text = "Name    Price
A       100
B       123
C       112
D       114
E       101
F       102", header=TRUE)
Vector = c(100,111)   

最新更新