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

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

示例:

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

class numeric 是许多 class 的一组。 class integerdouble 是其中两个子 class。 R 根据要求自动在不同的数字 classes 之间转换。