Home > Software engineering >  Conditionally replace values in one column/row with values from another row/column using dplyr
Conditionally replace values in one column/row with values from another row/column using dplyr

Time:04-08

I am trying to conditionally replace values in one column/row with values from another column/row using dplyr.

Here is a sample of the data:

  id          colours tagl  TAGLFT grid
  <fct>       <chr>   <chr> <chr> <chr>
  6391        B*/Y*   45820 45820  KL 
  6391        B*/Y*   45820 46272  KL
  8443        B*/Y*   46272 46272  SU

I am able to successfully replace within rows using this code:

updated<-df %>%
    mutate(tagl=ifelse(!tagl==TAGLFT, TAGLFT, tagl))

I look for any rows where tagl==TAGLFT and then replace tagl values with TAGLFT values. Then, if that condition is true (i.e., replacement has occurred), I need to also replace the id column with the correct id (these values are found in different rows).

Here is what I want:

  id          colours tagl  TAGLFT grid
  <fct>       <chr>   <chr> <chr> <chr>
  6391        B*/Y*   45820 45820  KL 
  8443        B*/Y*   46272 46272  KL
  8443        B*/Y*   46272 46272  SU

Any suggestions for how to work across rows? I work primarily in dplyr.

CodePudding user response:

How about this:

  library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
dat <- tibble::tribble(~id,          ~colours, ~tagl,  ~TAGLFT, ~grid,
"6391",        "B*/Y*",   "45820", "45820",  "KL", 
"6391",        "B*/Y*",   "45820", "46272",  "KL",
"8443",        "B*/Y*",   "46272", "46272",  "SU")

updated<-dat %>%
  mutate(tagl=ifelse(!tagl==TAGLFT, TAGLFT, tagl)) 

dat %>%
  filter(tagl == TAGLFT) %>% 
  select(TAGLFT, id) %>% 
  right_join(updated %>% select(-id)) %>% 
  select(id, colours, tagl, TAGLFT, grid)
#> Joining, by = "TAGLFT"
#> # A tibble: 3 × 5
#>   id    colours tagl  TAGLFT grid 
#>   <chr> <chr>   <chr> <chr>  <chr>
#> 1 6391  B*/Y*   45820 45820  KL   
#> 2 8443  B*/Y*   46272 46272  KL   
#> 3 8443  B*/Y*   46272 46272  SU

Created on 2022-04-05 by the reprex package (v2.0.1)

It works in this particular instance, you'll want to make sure it works on the full configuration of data that you have for your actual application.

  • Related