Home > OS >  update names based on columns R
update names based on columns R

Time:10-12

Following this question (update names based on columns), another thing that I want to ask

df <- data.frame(name1 = c("a", "a", "a", "a", 'a', NA, NA, NA,NA),
                 name2 = c("b", "b", "b", "b", "c", NA, NA, NA,NA),
                 name3 = c("b", "b", "b", "b", "c", "a", "a", "a", "f"))

df
  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     a
7  <NA>  <NA>     a
8  <NA>  <NA>     a
9  <NA>  <NA>     f

Now, I want to keep f while replacing a by b.

-Desired output

  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     b
7  <NA>  <NA>     b
8  <NA>  <NA>     b
9  <NA>  <NA>     f

The code from comments of @Rui and @TarJae

df %>% 
  mutate(name3 = case_when(
    any(name1 == "a") & is.na(name2) ~ "b",
    TRUE ~ name3
  ))

However, in this case, this does not work because I call NA from name2. Any sugesstions for me?

CodePudding user response:

If you just want to keep f, how about this?

edit except a and b will be not be changed.

df %>% 
  mutate(name3 = case_when(
    !(name3 %in% c("a", "b")) ~ name3,
    any(name1 == "a") & is.na(name2) ~ "b",
    TRUE ~ name3
  ))


  name1 name2 name3
1     a     b     b
2     a     b     b
3     a     b     b
4     a     b     b
5     a     c     c
6  <NA>  <NA>     b
7  <NA>  <NA>     b
8  <NA>  <NA>     b
9  <NA>  <NA>     f

CodePudding user response:

Generalizing the solution @Tjn25, one can do the following

f <- function(x) ifelse(x == "a", "b", x)

data.frame(lapply(df, f))

CodePudding user response:

If you just want to change the names3 column values that are a to b then you could use

df$name3[df$name3 == 'a'] <- 'b'
  • Related