Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

r - How to convert class of several variables at once

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...