替换使用 ifelse 不减少 R 中向量的长度?

Replace using ifelse not reduce length of vector in R?

我想根据每个级别和值的唯一截止值创建一个新列 new.val。如果,level = high 且 val > 35,则 new.val 为 0。如果,level = low 且 val > 30,则 new.val 为 0。

我尝试使用 ifelse 条件,但出现错误 Error in $<-.data.frame(tmp, new.val, value = c(0, 0, 0)) : replacement has 3 rows, data has 7.我如何 select 仅针对条件而不减小替换所需的数据帧的大小?

set.seed(111)
level <- c("high","high","high","high","low","low","low")
val <- rnorm(7,35,6)
df <- data.frame(level, val)
df$level <- as.factor(as.character(df$level))

#Creating new column
df$new.val <- df$val

#Conditions
df$new.val <- ifelse(df[df$val > 35 & df$level %in% c("high"),], 0, df$new.val)

Error in `$<-.data.frame`(`*tmp*`, new.val, value = c(0, 0, 0)) : 
replacement has 3 rows, data has 7


df$new.val <- ifelse(df[df$val > 30 & df$level %in% c("low"),], 0, df$new.val)

level      val    new.val
1  high 36.41132  0
2  high 33.01558  33.01558
3  high 33.13026  33.13026
4  high 21.18593  21.18593
5   low 33.97474  0
6   low 35.84167  0
7   low 26.01544  26.01544

我认为以下代码产生了理想的输出。

library(tidyverse)

set.seed(111)
level <- c("high","high","high","high","low","low","low")
val <- rnorm(7,35,6)
df <- data.frame(level, val)
df$level <- as.factor(as.character(df$level))

df$new.val <- df$val

    
df %>% 
  mutate(new.val = as.integer(case_when(
    
    val > 35 & level == "high" ~ 0, 
    val > 30 & level == "low" ~ 0,
    TRUE ~ new.val
    
  )))

  level      val new.val
1  high 36.41132       0
2  high 33.01558      33
3  high 33.13026      33
4  high 21.18593      21
5   low 33.97474       0
6   low 35.84167       0
7   low 26.01544      26