Duy Bui
Duy Bui

Reputation: 1396

R - Flatten a data frame within a list

I have received a JSON file which could be read into R as a list using

library(jsonlite)
data <- jsonlite::fromJSON(URL)

The data is a list which contains both data columns and data frame. For example

temp = list(id = c(1, 2, 3), name = c("banana", "organge", "apple"), type = data.frame(colour=c("red", "blue", "green", "purple"), shape = c("round", "round", "square", "square")))

> temp
$id
[1] 1 2 3

$name
[1] "banana"  "organge" "apple"  

$type
  colour  shape
1    red  round
2   blue  round
3  green square
4 purple square

How can we convert this list to data frame without losing information? In that case, I suppose each row in the nested data frame will be aligned with a row in the list. The result should be

   id    name type.colour type.shape
1   1  banana         red      round
2   1  banana        blue      round
3   1  banana       green     square
4   1  banana      purple     square
5   2  orange         red      round
6   2  orange        blue      round
7   2  orange       green     square
8   2  orange      purple     square
9   3   apple         red      round
10  3   apple        blue      round
11  3   apple       green     square
12  3   apple      purple     square

Upvotes: 0

Views: 172

Answers (1)

digEmAll
digEmAll

Reputation: 57220

For this specific case you can use the following code :

DFidxs <- rep(seq_len(nrow(temp$type)),times=length(temp$id))
colidxs <- rep(seq_len(length(temp$id)),each=nrow(temp$type))
DF <- cbind(id = temp$id[colidxs],
            name = temp$name[colidxs],
            temp$type[DFidxs,])

> DF
    id    name colour  shape
1    1  banana    red  round
2    1  banana   blue  round
3    1  banana  green square
4    1  banana purple square
1.1  2 organge    red  round
2.1  2 organge   blue  round
3.1  2 organge  green square
4.1  2 organge purple square
1.2  3   apple    red  round
2.2  3   apple   blue  round
3.2  3   apple  green square
4.2  3   apple purple square

assuming that id,name (and possibly other vectors/columns) have the same length you can reuse this code to replicate the lines of type data.frame for each element of the columns and bind them.

Upvotes: 1

Related Questions