# 基于来自不同小齿的截止值的小齿中不同列的变化值

##### 问题描述投票：2回答：1

``````library(lubridate)
library(tidyverse)

df <- tibble::tibble(date = seq.Date(ymd('2019-01-01'), ymd('2019-03-31'), by = 1),
high = sample(-5:100, 90, replace = T),
low = sample(-25:50, 90, replace = T),
sd = sample(5:25, 90, replace = T))
``````

``````cutoffs <- tibble::tibble(var_name = c('high', 'low', 'sd'),
min = c(0, -5, 10),
max = c(75, 15, 15))
``````

``````for (i in 1:3){

a <- cutoffs\$var_name[[i]]
print(a)
min <- cutoffs\$min[[i]]
max <- cutoffs\$max[[i]]

df <- df %>%
mutate(!!a := ifelse(!!as.name(a) < min, min, !!as.name(a)),
!!a := ifelse(!!as.name(a) > max, max, !!as.name(a)))

}
``````

r dplyr purrr
##### 1个回答
3

``````library(lubridate)
library(tidyverse)

df <- tibble::tibble(date = seq.Date(ymd('2019-01-01'), ymd('2019-03-31'), by = 1),
high = sample(-5:100, 90, replace = T),
low = sample(-25:50, 90, replace = T),
sd = sample(5:25, 90, replace = T)) %>%
pivot_longer(-date, names_to = "var_name", values_to = "value")

df

cutoffs <- tibble::tibble(var_name = c('high', 'low', 'sd'),
min = c(0, -5, 10),
max = c(75, 15, 15))

df %>%
left_join(cutoffs) %>%
mutate(value_new = case_when(value > max ~ max,
value < min ~ min,
TRUE ~ as.double(value))) %>%
select(date, var_name, value, value_new, min, max)
``````