首页 > 解决方案 > 根据预定义的阈值更新列的值

问题描述

我有一个数据集如下

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

标签: r

解决方案


这是一种方法

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)   

推荐阅读