R-不支持的索引类型:将列从因子转换为数字时列表错误



我正在尝试将一系列列从因子转换为数字。在此处运行第二行代码后,我会发现一个错误。

> 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

最新更新