r - How to convert class of several variables at once using dplyr -
so have data frame several variable characters want convert numeric. each of these variables starts "sect1". can 1 @ time, i'm wondering if can accomplished @ once.
i've done in clunky way using following code. maybe there's 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)
try mutate_each
, (as per @franks comment %<>%
operator magrittr
package in order modify in place)
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 data.table
package, modify data in place using :=
operator
library(data.table) indx <- grep("^sect1", names(df), value = true) setdt(df)[, (indx) := lapply(.sd, as.numeric), .sdcols = indx]
Comments
Post a Comment