R 将所有类型为 factor 的列更改为数字 [英] R change all columns of type factor to numeric

查看:32
本文介绍了R 将所有类型为 factor 的列更改为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 100 X 100 的数据框.有 30 列是因子.有没有办法只将因子类型的列切换到数字类型而不影响其他列(不走循环路线)?

I have a data frame that is 100 X 100. There are 30 columns that are factors. Is there a way to switch only factor-type columns to numeric type without affecting the other columns (without going the loop route)?

推荐答案

运用上面 Carl Witthoft 的智慧:

Applying the wisdom from Carl Witthoft above:

asNumeric <- function(x) as.numeric(as.character(x))
factorsNumeric <- function(d) modifyList(d, lapply(d[, sapply(d, is.factor)],   
                                                   asNumeric))

示例:

d <- data.frame(x=factor(1:3), y=factor(2:4), z=factor(3:5),
                r=c("a", "b", "c"), stringsAsFactors=FALSE)
> f <- factorsNumeric(d)
> class(f$x)
[1] "numeric"
> class(f$r)
[1] "character"

这篇关于R 将所有类型为 factor 的列更改为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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