简体   繁体   English

R中的字符串数组到数据帧的转换

[英]string array to data frame conversion in r

I have got this array in a string variable (k) and would like to convert it to a dataframe in r. 我已经在字符串变量(k)中获得了此数组,并希望将其转换为r中的数据帧。 The as.array(k) does not convert it. as.array(k)不会对其进行转换。 What is the best way to do this. 做这个的最好方式是什么。 Also, considering that there will be nested arrays in the future to be dealt with. 另外,考虑到将来会有嵌套数组要处理。

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]]

An option would be jsonlite to convert to a matrix , then change it to data.frame and retype 一个选项将是jsonlite转换为matrix ,然后将其更改为data.frameretype

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

Or this can be done with base R after removing the square brackets with regex 或者使用正则表达式删除方括号后,可以使用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

data 数据

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]]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM