dplyr:第一次满足条件时替换值

时间:2019-10-10 06:46:07

标签: r dplyr tidyverse

如何在tidyverse中执行以下base r操作?

res <- data.frame(distr=c(100,200,303,303,200,100),distr2=c(110,210,300,300,190,90)) 
res[which.max(res$distr),"distr2"] <- res[which.max(res$distr),"distr2"] + sum(res$distr)-sum(res$distr2)

2 个答案:

答案 0 :(得分:3)

不是专门使用tidyverse函数,但这是一种实现方法

library(dplyr)

res %>%
  mutate(distr2 = replace(distr2, which.max(distr), 
                distr2[which.max(distr)] + sum(distr) - sum(distr2)))


#  distr distr2
#1   100    110
#2   200    210
#3   303    306
#4   303    300
#5   200    190
#6   100     90

这是另一种方式

res %>%
    mutate(distr2 = distr2 + (row_number() == which.max(distr)) * 
                             (sum(distr) - sum(distr2)))

答案 1 :(得分:1)

看起来很奇怪,所以也许有更好的方法,但是您可以做到

res %>% 
  mutate(distr2 = if_else((1:n()) == which.max(distr), 
                          distr2  + sum(distr) - sum(distr2), 
                          distr2))