How to transform a class of multiple variables at once using dplyr
So I have a data frame with several variables, which are characters that I want to convert to numeric. Each of these variables starts with "sect1". I can do it easily one at a time, but I'm wondering if it is possible to do it all at once.
I did it awkwardly using the following code. Maybe there is a better way?
df=data.frame(sect1q1=as.character(c("1","2","3","4","5")),
sect1q2=as.character(c("2","3","4","7","8")),id=c(22,33,44,55,66),
stringsAsFactors = FALSE)
df1 = sapply(select(df,starts_with("sect1")),as.numeric)
df = select(df,-starts_with("sect1"))
df =cbind(df,df1)
+3
source to share
2 answers
Try it mutate_each
and (as per @Franks comment out statement %<>%
from package magrittr
for in-place change)
library(magrittr)
df %<>% mutate_each(funs(as.numeric), starts_with("sect1"))
str(df)
# 'data.frame': 5 obs. of 3 variables:
# $ sect1q1: num 1 2 3 4 5
# $ sect1q2: num 2 3 4 7 8
# $ id : num 22 33 44 55 66
Alternatively, using a package data.table
, you can change your details in place using the operator:=
library(data.table)
indx <- grep("^sect1", names(df), value = TRUE)
setDT(df)[, (indx) := lapply(.SD, as.numeric), .SDcols = indx]
+4
source to share