首页 > 解决方案 > 如何将具有逗号分隔值的因子转换为 R 中的数字向量?

问题描述

我从 json 文件导入数据,我需要一些元素作为数值。

json:

[
  {
    "a": 52,
    "b": 2020,
    "c": 14,
    "d": "1,2,3,4,5,6,7,8,9",
    "e": "4,1,2,3,1,0,0,0,0",
    "f": "TRUE"
  }
]

导入代码:

json_file <- fromJSON(file = "file")

json_file <- lapply(json_file, function(x) {
  x[sapply(x, is.null)] <- NA
  unlist(x)
})

json_file <-as.data.frame(do.call("rbind", json_file))

现在我要做的是从 d 中获取值并将它们转换为数字向量:

d_numeric <- as.numeric(json_file$d)

发生的错误是“强制引入的 NA”,问题似乎是 d 中的单个值由于逗号(下面的 str)而被视为一个级别。我怎样才能把它们分开?

str(json_file$d)
 Factor w/ 1 level "1,2,3,4,5,6,7,8,9": 1
 - attr(*, "names")= chr "Woche"

最好的问候索洛里

标签: rjsonimportnumeric

解决方案


推荐阅读