我已经将此数组放入字符串变量(k)中,并希望将其转换为r中的数据帧。 as.array(k)不会对其进行转换。做这个的最好方式是什么。另外,考虑到将来会有嵌套数组要处理。
places = [[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]
答案 0 :(得分:2)
可以选择jsonlite
转换为matrix
,然后将其更改为data.frame
和retype
library(jsonlite)
library(hablar)
library(dplyr)
fromJSON(places) %>%
as.data.frame %>%
retype
# A tibble: 4 x 5
# V1 V2 V3 V4 V5
# <chr> <chr> <int> <int> <int>
#1 Abtenau Abtenau 767 52 3
#2 Achenkirch Achenkirch am Achensee 248 61 6
#3 Adelharz Adelharz 47 46 2
#4 Alpbach Alpbachtal 2629 89 2
或者用正则表达式删除方括号后,可以用base R
完成
read.csv(text = gsub('[][]|"', "", gsub("(?<=\\]),(?=\\[)", "\n",
places, perl = TRUE)), header = FALSE, stringsAsFactors = FALSE)
# V1 V2 V3 V4 V5
#1 Abtenau Abtenau 767 52 3
#2 Achenkirch Achenkirch am Achensee 248 61 6
#3 Adelharz Adelharz 47 46 2
#4 Alpbach Alpbachtal 2629 89 2
places <- "[[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]"