如果一列中的前一个值大于另一列中的下一个值,则使其等于相应列中的值

if the previous value on one column is bigger than the next value in another column, make it equal to the value in corresponding column

我有一个这样的df

structure(list(id = c(1, 1, 1, 1, 2, 2, 2, 2), admi = c(50, 51, 
54, 93, 57, 160, 309, 321), dis = c(51, 127, 57, 94, 150, 410, 
313, 322)), class = "data.frame", row.names = c(NA, -8L))

并且我希望值按这样的递增顺序排列

structure(list(id = c(1, 1, 1, 1, 2, 2, 2, 2), admi2 = c(50, 
51, 54, 93, 57, 160, 309, 321), dis2 = c(51, 51.5, 57, 94, 150, 
160.5, 313, 322)), class = "data.frame", row.names = c(NA, -8L
))

基本上,如果 dis 列中 ID 的前一个值大于 adm 列中的下一个值,则使该 dis 值等于 admission 列中的值,并向其添加 0.5。谢谢 我尝试使用下面的代码

df <- df %>% 
  group_by(id) %>% 
  mutate(dplyr::across(c(dis, admi))) %>% 
  mutate(dis = ifelse(dis > lead(admi, default = first(admi)), admi + 0.5, dis))

这有效,但也出于某些原因,为条件甚至不为真的每个 ID 更改 dis 列中的最后一个值。 它给了我这个结果

structure(list(id = c(1, 1, 1, 1, 2, 2, 2, 2), admi = c(50, 51, 
54, 93, 57, 160, 309, 321), dis = c(51, 51.5, 57, 93.5, 150, 
160.5, 313, 321.5)), row.names = c(NA, -8L), groups = structure(list(
    id = c(1, 2), .rows = structure(list(1:4, 5:8), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

您可以利用 if_else 中的 missing 参数:

library(dplyr)

df %>% 
  group_by(id) %>% 
  mutate(dis = if_else(dis > lead(admi), admi + 0.5, dis, missing = dis)) %>%
  ungroup

#     id  admi   dis
#  <dbl> <dbl> <dbl>
#1     1    50  51  
#2     1    51  51.5
#3     1    54  57  
#4     1    93  94  
#5     2    57 150  
#6     2   160 160. 
#7     2   309 313  
#8     2   321 322