MIH
MIH

Reputation: 1113

Mutating chosen columns in the data.frame or tibble with dplyr package R

I would like to apply a mutate function to multiple columns at once. The columns start with certain string of characters and that is how they should be identified. I would like also to know the solution how to apply it to columns marked by indexing ie. data_fake[3:4]. The objective is to remove all the non-numeric characters and convert values to numeric. Can't make it work sadly. Desired result is given at the end of the code. Thanks a lot.

data_fake <- data.frame(c("1","2","NA","3,","2","1 only"),c(1,2,3,4,5,6),
                        c("23","3 bundles","4","5","NA","1"), c("3","5 packs","6","78","7","8"))
colnames(data_fake) <- c("AB foo ab", "AB foo bc", "CD foo ab","CD foo bc")

data_fake <- as_tibble(data_fake)

data_fake %>%
        select(starts_with("CD foo")) %>% 
        mutate(as.numeric(gsub("[^0-9]", "")))

data_fake_results <- as_tibble(data.frame(c("1","2","NA","3,","2","1 only"),c(1,2,3,4,5,6),
                        c(23,3,4,5,NA,1), c(3,5,6,78,7,8)))

Upvotes: 3

Views: 845

Answers (1)

akrun
akrun

Reputation: 887158

We can use mutate_at

library(tidyverse)
data_fake %>%
    mutate_at(vars(3:4), funs(as.numeric(str_remove(., "\\s+[a-z]+"))))

Or use parse_number

data_fake %>%
     mutate_at(3:4, parse_number)

If we want to match the column names in mutate_at

data_fake %>% 
    mutate_at(vars(starts_with("CD")), parse_number)

Upvotes: 5

Related Questions