【问题标题】:In R, convert list from API result into dataframe在 R 中,将列表从 API 结果转换为数据框
【发布时间】:2022-12-15 13:47:45
【问题描述】:

我正在尝试使用以下 API 获取一些数据。但是,结果以列表的形式出现,我无法将其转换为我可以使用的数据框。有人可以帮忙吗?

library(httr)
library(readxl)
library(tidyverse)
library(jsonlite)


resp <- GET("https://api.wto.org/timeseries/v1/data?i=ITS_CS_AX6&r=188,222,320,340,558,591,826&p=000&pc=SA,SB,SC,SD,SE,SF,SG,SH,SI,SJ,SK&ps=2010-2020&subscription-key=3134a3b9d8884ba991e0bfe2f2902c4f")

df<-fromJSON(rawToChar(resp$content))

如何将 df 转换为数据框?

非常感谢!

【问题讨论】:

  • 你能告诉我们resp 长什么样吗?如果不先看到结构,我们就无法提供帮助。

标签: r list api


【解决方案1】:

你几乎拥有它。如果你运行class(df),R 将返回list。如果用length(df) 查看列表的长度,它将返回1。如果你查看class(df[[1]]),你将得到data.frame。所以:

df <- df[[1]]


class(df)
# [1] "data.frame"

head(df)

#   IndicatorCategoryCode            IndicatorCategory IndicatorCode                                                  Indicator ReportingEconomyCode ReportingEconomy
# 1                ITS_CS Trade in commercial services    ITS_CS_AX6 Commercial services exports by sector and partner – annual                  320        Guatemala
# 2                ITS_CS Trade in commercial services    ITS_CS_AX6 Commercial services exports by sector and partner – annual                  320        Guatemala
# 3                ITS_CS Trade in commercial services    ITS_CS_AX6 Commercial services exports by sector and partner – annual                  320        Guatemala
# 4                ITS_CS Trade in commercial services    ITS_CS_AX6 Commercial services exports by sector and partner – annual                  320        Guatemala
# 5                ITS_CS Trade in commercial services    ITS_CS_AX6 Commercial services exports by sector and partner – annual                  320        Guatemala

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2018-03-14
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    相关资源
    最近更新 更多