LDT
LDT

Reputation: 3088

Convert any element that does not start with a specific string to NA

I have a large data frame that looks like df2. I want to convert any element across columns code1, code2 that does not start with AT to NA.

library(tidyverse)

df2 <- tibble(type=c("Jeep", "4x4", "convertible"), 
              code1=c("ATG1",NA, "ATG2"), 
              code2=c("random", "ATG3", "xyz"))
df2
#> # A tibble: 3 × 3
#>   type        code1 code2 
#>   <chr>       <chr> <chr> 
#> 1 Jeep        ATG1  random
#> 2 4x4         <NA>  ATG3  
#> 3 convertible ATG2  xyz

Created on 2022-09-29 with reprex v2.0.2

I want my data to look like this #> type code1 code2 #> #> 1 Jeep ATG1 NA #> 2 4x4 ATG3
#> 3 convertible ATG2 NA

Upvotes: 1

Views: 38

Answers (3)

akrun
akrun

Reputation: 887028

Using case_when

library(dplyr)
library(stringr)
df2 %>%
   mutate(across(starts_with('code'), ~ case_when(str_detect(.x, '^AT')~ .x)))

-output

# A tibble: 3 × 3
  type        code1 code2
  <chr>       <chr> <chr>
1 Jeep        ATG1  <NA> 
2 4x4         <NA>  ATG3 
3 convertible ATG2  <NA> 

Upvotes: 1

Ma&#235;l
Ma&#235;l

Reputation: 51914

With replace and grepl:

df2 %>% 
  mutate(across(starts_with("code"), ~ replace(.x, !grepl("^AT", .x), NA)))

Upvotes: 2

Allan Cameron
Allan Cameron

Reputation: 173793

You could do

df2 %>%
  mutate(across(code1:code2, ~ifelse(substr(.x, 1, 2) == 'AT', .x, NA)))
#> # A tibble: 3 x 3
#>   type        code1 code2
#>   <chr>       <chr> <chr>
#> 1 Jeep        ATG1  NA   
#> 2 4x4         NA    ATG3 
#> 3 convertible ATG2  NA  

Upvotes: 3

Related Questions