r - 不支持的索引类型 : list error when converting columns from factors to numerics

标签 r error-handling

我正在尝试将一系列列从因子转换为数字。在这里运行第二行代码后,出现错误。

> cols.num<-c(df[19:59],df[75:94])
> df[cols.num] <- sapply(df[cols.num],as.numeric)
Error: Unsupported index type: list

如何解决此错误,以便将 cols.num 中的列转换为数值变量?

编辑:这是一些数据的示例。

A1U_sweet  A2F_dip  A3U_bbq  C1U_sweet  C2F_dip  C3U_bbq  B1U_sweet  B2F_dip
1          2        1        NA         NA       NA       1          2
NA         NA       NA       4          1        2        4          1
2          4        7        NA         NA       NA       2          4

最佳答案

cols.num 应该是列索引的向量。相反,它是该列的值列表。

这是问题的示例。

df <- as.data.frame(matrix(runif(15), ncol = 5))
df
#>          V1        V2        V3        V4        V5
#> 1 0.3539401 0.8420100 0.7615357 0.6313510 0.8367287
#> 2 0.7218828 0.4994062 0.8193055 0.9419635 0.3552728
#> 3 0.6302484 0.9259249 0.5634492 0.9034216 0.8514657

cols.num <- c(df[1:2],df[4:5])
df[cols.num] <- sapply(df[cols.num], as.integer)
#> Error in `[.default`(df, cols.num) : invalid subscript type 'list'

如果我们查看col.num,它是列值的列表。

cols.num
#> $V1
#> [1] 0.3539401 0.7218828 0.6302484
#> 
#> $V2
#> [1] 0.8420100 0.4994062 0.9259249
#> 
#> $V4
#> [1] 0.6313510 0.9419635 0.9034216
#> 
#> $V5
#> [1] 0.8367287 0.3552728 0.8514657

要修复此问题,只需创建列索引的向量即可。

cols.num <- c(1:2, 4:5)
df[cols.num] <- sapply(df[cols.num], as.integer)
df
#>   V1 V2        V3 V4 V5
#> 1  0  0 0.7615357  0  0
#> 2  0  0 0.8193055  0  0
#> 3  0  0 0.5634492  0  0

关于r - 不支持的索引类型 : list error when converting columns from factors to numerics,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716139/

相关文章:

r - 使用 row, col 索引从矩阵中索引值

r - 如何将 %LET 参数从 R 传递到 sas 脚本?

angularjs - Angular 中全局错误处理的合理方法

ruby-on-rails - 处理独特的错误

exception - Common Lisp 错误处理系统中 'store-value' 和 'use-value' 重新启动的语义

javascript - 如何处理Express API中的多个错误?例如我要处理404,405,400和500

r - 使用 ggplot2 进行多变量回归

r - 不懂R的apply函数

r - 使用 Windows (TTF) 字体?

laravel - 缺少[Route : roles.destroy]的必填参数