如果满足条件则全部替换但如果满足另一个条件则不替换R中的dplyr

if condition is met replace all but not if another condition is met dplyr in R

我正在尝试将 nat_locx 中的所有值替换为 LOCX 中第一行的值,如果满足第一个条件,则将所有 distance 值替换为 0 id(我的 group_by() 变量)或多次,但如果 id.

满足我的第二个条件一次或多次,则不会

这是我的数据示例:

  id         DATE       nat_locx  LOCX distance loc_age  condition
 <fct>       <date>        <dbl> <dbl>    <dbl>   <dbl>  <lgl>
 6553        2004-06-27     13.5   2    487.90       26  TRUE
 6553        2004-07-14     13.5  13.5    0          43  FALSE
 6553        2004-07-15     13.5  12.5   30          44  FALSE  
 10160       2005-07-01      4.5    12 229.45588     36  TRUE          
 10160       2005-07-05      4.5    11 200.12496     40  TRUE     
 10160       2005-07-06      4.5    11 200.12496     41  TRUE

我尝试这样做的方式是这样的:

df<-df %>%
  group_by(id) %>%
  mutate(condition = case_when(     
    loc_age >= 25 & loc_age < 40 & distance > 30 ~ TRUE, 
    loc_age>=40 & loc_age<50 & distance>60 ~ TRUE,
    TRUE ~ FALSE)) %>%  
mutate(nat_locx=if(condition=="TRUE") {
        first(LOCX) & distance==0.00
        } else {
        nat_locx})

第一个 mutate() 生成一个包含 TRUEFALSE 值的新列。如果FALSE只有一个实例,那么我后面写的if else语句应该不会继续。

在这个例子中,这意味着对于 id==6553 循环不应该改变任何东西。但是,因为 condition==TRUE 对于 id==10160 的每一行,那么 if else 应该继续。

理想情况下,我想要这样的输出:

  id         DATE       nat_locx  LOCX distance loc_age  condition
 <fct>       <date>        <dbl> <dbl>    <dbl>   <dbl>  <lgl>
 6553        2004-06-27     13.5   2    487.90       26  TRUE
 6553        2004-07-14     13.5  13.5    0          43  FALSE
 6553        2004-07-15     13.5  12.5   30          44  FALSE  
 10160       2005-07-01      12    12     0          36  TRUE          
 10160       2005-07-05      12    11     0          40  TRUE     
 10160       2005-07-06      12    11     0          41  TRUE

首选 dplyr 解决方案。

正如@Ben 所提到的,我们可以包含 all,以便更改仅适用于全部 TRUE 的组。我们可以将其用于 nat_locxdistance 列。

library(tidyverse)


df %>%
  group_by(id) %>%
  mutate(
    condition = case_when(
      loc_age >= 25 & loc_age < 40 & distance > 30 ~ TRUE,
      loc_age >= 40 & loc_age < 50 & distance > 60 ~ TRUE,
      TRUE ~ FALSE
    )
  ) %>%
  mutate(nat_locx = if (all(condition)) first(LOCX) else nat_locx,
         distance = if (all(condition)) 0 else distance)

输出

     id DATE       nat_locx  LOCX distance loc_age condition
  <int> <chr>         <dbl> <dbl>    <dbl>   <int> <lgl>    
1  6553 2004-06-27     13.5   2       488.      26 TRUE     
2  6553 2004-07-14     13.5  13.5       0       43 FALSE    
3  6553 2004-07-15     13.5  12.5      30       44 FALSE    
4 10160 2005-07-01     12    12         0       36 TRUE     
5 10160 2005-07-05     12    11         0       40 TRUE     
6 10160 2005-07-06     12    11         0       41 TRUE