我使用GET function
和httr
包来自网站的数据集,但数据现在采用如下字符格式。如何将其转换为表格以便我可以绘制?非常感谢!
print(resContent)
[1] "{\"pTType\":\"line\",\"gBType\":\"line\",\"data\":[[9624,8873,8671,8420,8452,8718,9712,10373,11061,11708,11253,10482,10780,10829,10884,11318,10849,10732],[1635,1244,1361,1493,1695,1478,1838,1787,1824,1985,1983,1802,2030,2253,2251,2127,1972,2023]]}"
> length(resContent)
[1] 1
> typeof(resContent)
[1] "character"
答案 0 :(得分:0)
我假设前两个元素的名称是列的名称,但我不确定这是一个可靠的假设。无论如何,下面的代码应该让你朝着正确的方向前进。
library(rjson)
library(magrittr)
resContent <- "{\"pTType\":\"line\",\"gBType\":\"line\",\"data\":[[9624,8873,8671,8420,8452,8718,9712,10373,11061,11708,11253,10482,10780,10829,10884,11318,10849,10732],[1635,1244,1361,1493,1695,1478,1838,1787,1824,1985,1983,1802,2030,2253,2251,2127,1972,2023]]}"
rjson::fromJSON(resContent)$data %>%
as.data.frame() %>%
setNames(c("PTType", "gBType"))
答案 1 :(得分:0)
以下内容将从您提供的字符串中提取逗号分隔的数字,并返回一个数字向量:
as.numeric(unlist(strsplit(gsub("^.*\\[(\\d.*)\\]\\].*$", "\\1", resContent), split=",")))
[1] 1635 1244 1361 1493 1695 1478 1838 1787 1824 1985 1983 1802 2030 2253 2251 2127 1972 2023
gsub
提取子表达式(逗号分隔数字的子串),strsplit
将其分为逗号,unlist
返回存储为字符as.numeric
将这些转换为数字向量。