【问题标题】:Unsupported index type: list error when converting columns from factors to numerics不支持的索引类型:将列从因子转换为数字时出现列表错误
【发布时间】:2018-02-10 00:53:07
【问题描述】:

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

> 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 不是你想要的,它是一个列表。向我们展示您的一些数据会有所帮助。
  • @kgolyaev 我添加了一些数据的示例。

标签: r error-handling


【解决方案1】:

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

【讨论】:

  • 这成功了!只是好奇:您将 as.numeric 更改为 as.integer 有什么原因吗?
  • 我只是为了示例而对其进行了更改。只是为了显示哪些列发生了变化。如果将数字更改为数字,则不会显示任何差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 2021-09-03
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多