RichS
RichS

Reputation: 669

Extracting elements from a jsonlite parsed list in R

I have imported data from a .json file into R via jsonlite. Unfortunately the data shows up as a 'List of 1' even though it contains multiple categories.

library(jsonlite)
wimbledon <- from JSON("wimbledon.json",flatten=TRUE)

I get the following when I open wimbledon in the global environment:

wimbledon                      List of 1
 graph_data: 'data.frame': 1 obs. of 2 variables:
 ..$ term:chr "wimbledon"
 ..$data: List of 1
 .. ..$: 'data.frame': 165 obs. of 3 variables:
 .. .. ..$ matches : int [1:165] 0 0 0 0 0 0 0 0 ...
 .. .. ..$ year : int [1:165] 1851 1852 1853 1854 ...

My question is, is there any easy way to reference only the $matches and $year as I would do in a data frame using wimbledon$matches and wimbledon$year? I am familiar with using wimbledon[[n]] to extract a certain element of a list. However, the issue here is that I seem to have parsed everything into a single list in jsonlite. Apologies that I cannot add a reproducible example. Any help you can give me in extracting the 'matches' and 'year' columns as separate data frame columns would be greatly appreciated.

Upvotes: 1

Views: 1878

Answers (1)

mattdevlin
mattdevlin

Reputation: 1095

When there are unnamed values in a list e.g.$: 'data.frame': 165 obs. of 3 variables:, the var[[n]] syntax is needed so

wimbledon$graph_data$data[[1]]$matches

and

wimbledon$graph_data$data[[1]]$year

will return the matches and years.

Upvotes: 1

Related Questions