Nested if and max if statement in R error: unused argument

Nested if and max if statement in R error: unused argument

对 R 还是很陌生,我想在另一个变量为 postive/negative 时确定组内变量的最大值。具体来说,if l_diff<0,我想在pos_n<0时,找到每组中t的最大值。如果l_diff>0,我想在pos_p>0时,找到每个组中t的最大值。示例数据:

l_diff <- c(-1,-1,-1,-1,-1,-1,1,1,1,1,1)
pos_n <- c(2,2,1,-4,-2,-2,2,1,-5,4,8)
pos_p <- c(3,4,-5,6,-7,2,-3,3,2,1,4)
t <- c(5,7,3,1,6,2,7,5,3,2,1)
group <- c(1,1,1,1,1,1,2,2,2,2,2)
db <- data.frame(cbind(l_diff,pos_n, pos_p, t, group))

期望的输出:

cmax<- c(6,6,6,6,6,6,5,5,5,5,5)

我尝试了以下方法:

db<-db %>%
  group_by((group)) %>%
  mutate(ifelse(l_diff<0, t1 = max(t[pos_n<0], ifelse(l_diff>0, t1 = max(t[pos_p >0])))))

但是我得到以下错误:

Error: Problem with mutate() input ..1. x unused argument (t1 = max(t[pos_n < 0], ifelse(l_diff > 0, t1 = max(t[pos_p > 0])))) i Input ..1 is ifelse(...). i The error occurred in group 1: (group) = 1.

知道哪里有问题或有任何其他建议吗?

使用ifelse,我们需要将赋值放在外面,同样,ifelse用法中的所有参数都必须存在

ifelse(test, yes, no)

此处,在嵌套的第二个 ifelse 中找不到 no。如果我们使用 case_when 作为默认 TRUE ~ NA

这不是问题
library(dplyr)
db %>%
   group_by(group) %>%
   mutate(t1  = ifelse(l_diff<0,  max(t[pos_n<0]), 
                ifelse(l_diff>0,max(t[pos_p >0]), NA))) %>%
   ungroup

-输出

# A tibble: 11 x 6
#   l_diff pos_n pos_p     t group    t1
#    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1     -1     2     3     5     1     6
# 2     -1     2     4     7     1     6
# 3     -1     1    -5     3     1     6
# 4     -1    -4     6     1     1     6
# 5     -1    -2    -7     6     1     6
# 6     -1    -2     2     2     1     6
# 7      1     2    -3     7     2     5
# 8      1     1     3     5     2     5
# 9      1    -5     2     3     2     5
#10      1     4     1     2     2     5
#11      1     8     4     1     2     5