首页 > 解决方案 > 使用循环将选定的数据框列转换为因子?

问题描述

我有一个数据框df。除了选择数字列之外,它还包含大部分因素。

我想创建一个数据质量报告,并且所有内容都以整数形式读取。所以我捕获了以下列索引,并希望将这些列转换为类型因子:

n_cols = c(1,3,4,9:17,28:35)

for (x in length(df)) {
  if (x %in% n_cols == FALSE) {
    df[,x] = as.factor(df[,x])
  }
}

代码正在运行,但是当我调用str(df).

我来自 Python 背景,所以其中一些语法对我来说比较新。

标签: r

解决方案


要将数据框中的选定列转换为 for 循环中的因子,我在下面使用mtcars数据集创建了一个可重现的示例。

注意:这取决于指定要强制转换为因子的列号向量。如果你想反转这个逻辑,你可以!在 if() 语句中插入一个来否定逻辑。

# example data
data(mtcars)

# columns to go to factors
to_fact <- c(1, 3, 5, 7)

for(x in seq_along(mtcars)) {
  if(x %in% to_fact){
    mtcars[,x] <- as.factor(mtcars[,x]) 
  }
}

str(mtcars)
#> 'data.frame':    32 obs. of  11 variables:
#>  $ mpg : Factor w/ 25 levels "10.4","13.3",..: 16 16 19 17 13 12 3 20 19 14 ...
#>  $ 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 ...
#>  $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
#>  $ drat: Factor w/ 22 levels "2.76","2.93",..: 16 16 15 5 6 1 7 11 17 17 ...
#>  $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
#>  $ qsec: Factor w/ 30 levels "14.5","14.6",..: 6 10 22 24 10 29 5 27 30 19 ...
#>  $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
#>  $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
#>  $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
#>  $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

reprex 包(v0.2.0)于 2018 年 8 月 31 日创建。

为了更简洁地完成此操作,您还可以使用该purrr包进行函数式编程:

mtcars[to_fact] <- purrr::map_df(mtcars[to_fact], as.factor)

推荐阅读