代码之家  ›  专栏  ›  技术社区  ›  rmahesh

是否使用循环将选定的数据帧列转换为因子?

r
  •  0
  • rmahesh  · 技术社区  · 6 年前

    我有一个数据帧 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的背景,所以有些语法对我来说比较新。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Dean    6 年前

    将数据框中的选定列转换为因子的步骤 下面我用 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 package (第0.2.0版)。

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

    mtcars[to_fact] <- purrr::map_df(mtcars[to_fact], as.factor)
    
        2
  •  0
  •   smci    6 年前

    sapply/lapply

    mtcars[,factorCols] <- lapply(mtcars[,factorCols], as.factor)
    

    2) 更长的选择:不需要嵌套 for-if ;您知道要转换的列的特定列索引。所以直接迭代它们,已经:

    data(mtcars)
    factorCols <- c(1,3,5,7)
    
    for (factorCol in factorCols) {
      mtcars[, factorCol] <- as.factor(mtcars[, factorCol])
    }
    

    基本上是一条直线。