如何一次转换几个变量的类 [英] How to convert class of several variables at once

查看:78
本文介绍了如何一次转换几个变量的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个带有几个变量的数据框,这些变量是要转换为数字的字符。这些变量均以 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)


推荐答案

尝试 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆