提问人:stats_noob 提问时间:8/17/2022 最后编辑:stats_noob 更新时间:8/17/2022 访问量:1168
R:参数“txt”必须是 JSON 字符串、URL 或文件
R : Argument 'txt' must be a JSON string, URL or file
问:
我正在使用 R 编程语言。我有一个列表对象(“my_list”),如下所示:
[[1]]
Response [https://abc]
Date: 2022-08-17 02:33
Status: 200
Content-Type: application/json; charset=utf-8
Size: 271 B
{
"var1": "abc.123",
"var2": "abc",
"var3": "abc",
"var4": "abc",
"var5": "11.22, 33.44"
[[2]]
Response [https://abd]
Date: 2022-08-17 02:33
Status: 200
Content-Type: application/json; charset=utf-8
Size: 270 B
{
"var1": "abd.123",
"var2": "abd",
"var3": "abd",
"var4": "abd",
"var5": "11.33,44.55"
[[3]]
Response [https://def]
Date: 2022-08-17 02:33
Status: 200
Content-Type: application/json; charset=utf-8
Size: 320 B
{
"var1": "def.123",
"var2": "def",
"var3": "def",
"var4": "def",
"var5": "55.66, 77.88"
...
我想将其转换为一个数据框,其中列是“var1、var2、var3、var4、var5、var6(拆分 var 5)”,每行都是列表的索引(例如 [[1]]、[[2]]、[[3]] 等)。这看起来像这样:
index var1 var2 var3 var4 var5 var6
1 1 abc.123 abc abc abc 11.22 33.44
2 2 abd.123 abd abd abd 11.33 44.55
3 3 def.123 def def def 55.66 77.88
通常,我会做这样的事情 - 但我收到以下错误:
data_frame = do.call(rbind.data.frame, my_list)
Error in (function (..., deparse.level = 1, make.row.names = TRUE, stringsAsFactors = FALSE, :
invalid list argument: all variables should have the same length
然后我想,由于此列表似乎是JSON格式,也许我应该尝试此链接中建议的方法(如何在R中将Json转换为数据帧) - 但是我现在收到一个新错误:
fromJSON(my_list) %>% as.data.frame
Error: Argument 'txt' must be a JSON string, URL or file.
有人可以告诉我我做错了什么以及我该如何解决这个问题吗?
谢谢!
答:
1赞
dcsuka
8/17/2022
#1
fromJSON
不可矢量化,因此您必须将其与它一起使用:lapply
my_list <- list('{
"var1": "abd.123",
"var2": "abd",
"var3": "abd",
"var4": "abd",
"var5": "11.33,44.55"}',
'{
"var1": "abd.123",
"var2": "abd",
"var3": "abd",
"var4": "abd",
"var5": "11.33,44.55"}',
'{
"var1": "abd.123",
"var2": "abd",
"var3": "abd",
"var4": "abd",
"var5": "11.33,44.55"}')
lapply(my_list, function(x) as.data.frame(fromJSON(x))) %>%
dplyr::bind_rows()
# var1 var2 var3 var4 var5
# 1 abd.123 abd abd abd 11.33,44.55
# 2 abd.123 abd abd abd 11.33,44.55
# 3 abd.123 abd abd abd 11.33,44.55
评论
0赞
stats_noob
8/17/2022
@dcsuka:谢谢你的回答!我尝试了您的代码并收到以下错误错误:参数“txt”必须是 JSON 字符串、URL 或文件。- 还有什么我可以尝试的吗?非常感谢!
1赞
dcsuka
8/17/2022
你能发送一个你的json列表吗?或者我们可以以某种方式看待同样的事情?如果您直接从 URL 作为 ,而不是像 first 那样做一些事情,那就更容易了。dput
fromJSON
httr::GET
0赞
stats_noob
8/17/2022
你的第二个想法真是个好主意!我现在就试试!
0赞
dcsuka
8/17/2022
是的,尝试将 URL 列表放入同一个 lapply。
评论