Search code examples
rwhere-clausedplyrcoercionacross

Function to coerce strings given a condition


I simply want to coerce as numbers --i.e., to apply as.numeric to--any columns which have a 1 as their first entry (i.e., a character). So I would expect to turn:

tibble(a = c("1", "2"), b = c("Fred", "Kevin"), c = 1:2)

into

tibble(a = 1:2, b = c("Fred", "Kevin"), c = 1:2)

Solution

  • You could use dplyr:

    library(dplyr)
    
    data %>% 
      mutate(across(where(~ first(.x) == "1" & !is.na(first(.x))), as.numeric)).
    

    returns

    # A tibble: 2 x 5
          a b         c     d e    
      <dbl> <chr> <dbl> <dbl> <lgl>
    1     1 Fred      1     1 NA    
    2     2 Kevin     2     3 NA   
    

    Data

    data <- tibble(a = c("1", "2"), 
                   b = c("Fred", "Kevin"), 
                   c = 1:2, 
                   d = c("1", "3"), 
                   e = c(NA, NA))