Home > Mobile >  Mutate across columns and replace entries with case_when
Mutate across columns and replace entries with case_when

Time:05-11

I'm trying to change cell entries when a column and cell meets criteria.

Data:

df <- data.frame(a=c("a", "ab", "ac"), b=c("b", "bc", NA), c=c("c", NA, "cda"))
> df
   a    b    c
1  a    b    c
2 ab   bc <NA>
3 ac <NA>  cda

Attempt:

> df %>% mutate(across(matches("b", "c"), ~case_when(. %in% "c" & is.na(.) ~ "here", TRUE ~ as.character(.))))
   a    b    c
1  a    b    c
2 ab   bc <NA>
3 ac <NA>  cda

Looking for this:

   a    b    c
1  a    b    c
2 ab   bc  here
3 ac  here  cda

CodePudding user response:

Try this:

library(tidyverse)

data.frame(a=c("a", "ab", "ac"), b=c("b", "bc", NA), c=c("c", NA, "cda")) |> 
  mutate(across(everything(), ~if_else(is.na(.), "here", .)))
#>    a    b    c
#> 1  a    b    c
#> 2 ab   bc here
#> 3 ac here  cda

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

CodePudding user response:

In base R :

df[, c("b", "c")][is.na(df[, c("b", "c")])] <- "here"

CodePudding user response:

Just declare the variables in aqcross, i.e.

df %>% 
 mutate(across(c('b', 'c'), ~replace(., is.na(.), 'here')))

   a    b    c
1  a    b    c
2 ab   bc here
3 ac here  cda
  • Related