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
解决方案
这是一种方法
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)
推荐阅读
- c# - Microsoft Bot Framework 的频道注册列表中缺少 Telegram 频道选项
- python - ValueError:时间数据“2017-02-22”与格式“%d-%m-%Y”不匹配
- azure - Azure 函数看不到从 Shopify 正确传递的 JSON 正文
- javascript - 然后插入子文档
- html - css获取较小的:宽度或高度
- java - 在 Java 中使用 PrintWriter 编写多行
- flutter - 如何正确开始和结束或动画和更改其他类颤动的文本
- python - 如何解决属性错误'QueryDict'对象没有属性'company'?
- discord - 我想将我的不和谐机器人状态从播放更改为观看
- windows - 为什么系统找不到指定的路径?