如何一次转换多个变量的类 [英] How to convert class of several variables at once
问题描述
所以我有一个包含几个变量的数据框,这些变量是我想转换为数字的字符.这些变量中的每一个都以sect1"开头.我可以轻松地一次完成一个,但我想知道这是否可以一次完成.
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)
推荐答案
Try mutate_each
和(根据@Franks 注释,%<>%
操作符来自magrittr
包以便就地修改)
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
或者,使用 data.table
包,您可以使用 :=
运算符就地修改数据
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]
这篇关于如何一次转换多个变量的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!