Reputation: 315
So I have a data frame with several variable that are characters that I want to convert to numeric. Each of these variables starts with "sect1". I can do this easily one at a time, but I'm wondering if this can be accomplished all at once.
I've done this in a clunky way using the following code. Maybe there's 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)
Upvotes: 3
Views: 629
Reputation: 92282
Try mutate_each
and (as per @Franks comment the %<>%
operator from the magrittr
package in order to 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, you could modify your data in place using the :=
operator
library(data.table)
indx <- grep("^sect1", names(df), value = TRUE)
setDT(df)[, (indx) := lapply(.SD, as.numeric), .SDcols = indx]
Upvotes: 5
Reputation: 3188
Here is an solution with base R
df[, grepl("sect1", names(df))] <- lapply(df[, grepl("sect1", names(df))], as.factor)
Change as.factor
to as.numeric
for numeric
Upvotes: 2