Home > front end >  In R, convert list from API result into dataframe
In R, convert list from API result into dataframe

Time:12-14

I am trying to use the following API to get some data. However the results come as a list of lists, and I am having trouble converting it into a dataframe I can use. Can anyone please help?

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

How do I turn df into a dataframe?

Thanks a lot!

resp looks like this: enter image description here

CodePudding user response:

You almost had it. The jsonlite::fromJSON() function is great but if you are not sure about the structure of the input, the output can be unpredictable. However it's usually a pretty good first step.

In your case, if you run class(df) R will tell you that you have a list. If you look at the length of the list with length(df), it will return 1. If you look at class(df[[1]]) you will get data.frame. So:

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
  • Related