Replace with NA

Hi,

I've got stuck by trying to replace all values in my df containg "," by NAs. Could you please help me, preferably in dplyr?

Many thanks,

Jakub

Have you tried a combination of dplyr's mutate( ) + across ( ) + case_when( ) functions?

1 Like

Here is one solution that acts only on character columns.

library(dplyr)
library(stringr)
DF <- data.frame(A = c("A", "B,C", "C"),
                 B = c("1", "2", "3,4"),
                 C = rnorm(3))
DF
#>     A   B          C
#> 1   A   1  0.5281151
#> 2 B,C   2  0.8441517
#> 3   C 3,4 -1.7556551
DF <- DF |> mutate(across(where(is.character), 
                          ~ifelse(str_detect(.x, ","), NA, .x)))
DF
#>      A    B          C
#> 1    A    1  0.5281151
#> 2 <NA>    2  0.8441517
#> 3    C <NA> -1.7556551

Created on 2022-07-08 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.