R将类型因子的所有列更改为数值。

时间:2022-11-15 07:36:11

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)?

我有一个100 X 100的数据帧。有30个列是因数。是否有一种方法可以在不影响其他列的情况下(不使用循环路由)将只对类型的列转换为数值类型?

2 个解决方案

#1


25  

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))

Example:

例子:

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"

#2


15  

See R-FAQ 7.10 at cran.r-project.org http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f

见R-FAQ 7.10在cran.r-project.org http://cran.r project.org/doc/faq/rfaq.html # how- do- convertfactors-to numeric_003f。

ALWAYS do as.numeric(as.character(some_Factor)) or you will be sorry.

总是做。数字(字符(some_Factor))或你会感到抱歉。

#1


25  

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))

Example:

例子:

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"

#2


15  

See R-FAQ 7.10 at cran.r-project.org http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f

见R-FAQ 7.10在cran.r-project.org http://cran.r project.org/doc/faq/rfaq.html # how- do- convertfactors-to numeric_003f。

ALWAYS do as.numeric(as.character(some_Factor)) or you will be sorry.

总是做。数字(字符(some_Factor))或你会感到抱歉。