繁体   English   中英

R:如何将因子转换为数值?

[英]R: How to convert factors into numeric for a DATA FRAME?

我想将因子转换为数值。 我知道这是一个常见问题解答,我已经尝试过as.numeric(levels(f))[f]as.numeric(as.character(f)) 但这无济于事,因为我想将df的所有列(超过1000和所有类型因子)转换为数值。 我怎样才能做到这一点?

我们可以试试

 yourdat[] <- lapply(yourdat, function(x) if(is.factor(x)) as.numeric(levels(x))[x]
                              else x)

尝试这个:

for(name in names(df)){
    if(is.factor(df[[name]])){
        class(df[[name]]) <- "numeric"
        #df[[name]] <- as.numeric(df[[name]])
    }
}

在上述解决方案中,您可以将df[[name]] <- as.numeric(df[[name]])替换class(df[[name]]) <- "numeric" 两者都会给出相同的结果。

例:

mtcars_copy <- data.frame(mpg = mtcars$mpg, cyl = mtcars$cyl, disp = as.factor(mtcars$disp))

str(mtcars_copy)
## 'data.frame':    32 obs. of  3 variables:
## $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
## $ disp: Factor w/ 27 levels "71.1","75.7",..: 13 13 6 16 23 15 23 12 10 14 ...

for(name in names(mtcars_copy)){
    if(is.factor(mtcars_copy[[name]])){
        mtcars_copy[[name]]) <- as.numeric(mtcars_copy[[name]])
    }
}

class(mtcars_copy$disp)
## [1] "integer"

str(mtcars_copy)
## 'data.frame':    32 obs. of  3 variables:
## $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
## $ disp: int  13 13 6 16 23 15 23 12 10 14 ...

numeric类是许多类的集合。 integerdouble是这些子类中的两个。 R根据要求自动在不同的数字类之间转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM