2
votes

I have a data frame that has a bunch of columns. Some of the columns end with a _id. For example, food_id, drink_id. I want to convert the data in all columns that end with "_id" from Factors to numeric. How would I go about doing that in dplyr?

1

1 Answers

3
votes

We can use mutate_at

library(dplyr)
library(magrittr)
df1 %<>%
   mutate_at(vars(ends_with("_id")), funs(as.numeric(as.character(.))))

If we want to select specific 'id' columns

df2 %<>% 
  mutate_at(vars(matches("^(food|drink).*_id")), funs(as.numeric(as.character(.))))

Or the reverse logic

df2 %<>% 
  mutate_at(vars(ends_with("_id"), -matches("^(snack|dessert).*_id")),
                funs(as.numeric(as.character(.))))

Or create an index of columns before with grep and then use that in mutate_at

i1 <- !grepl("^(snack|dessert).*_id$", names(df2)) & grepl("_id$", names(df2))
df2 %<>%
     mutate_at(vars(which(i1)), funs(as.numeric(as.character(.)))) 

data

set.seed(24)
df1 <- data.frame(food_id = factor(1:5), drink_id = factor(6:10), value = rnorm(5))


df2 <- data.frame(food_id = factor(1:5), drink_id = factor(6:10), value = LETTERS[1:5],
snack_id = factor(1:5),  dessert_id = factor(11:15))