Home > Software engineering >  Convert list from API do dataframe
Convert list from API do dataframe

Time:08-22

I have a data as a list which looks like as following.

name                   type              value
Api_collect            list [5]          List of length 5
 country               character [1]        US
 state                 character [1]        Texas
 computer              character [1]        Mac
 house                 character [1]        Mansion
 president             character [1]        Trump

The following code have I runned in R.

api_col <- base::rawToChar((response$country))

as.data.frame(api_json$country)

And results in this df:

country
US

What I would like to to is to transfer this list to a dataframe with every column of Api_collect except for house. How do I do that?

CodePudding user response:

# Is this example any good?
TEST <- list(c(1,2,3),c(4,5,6),c(5,6,7)) # create list
names(TEST) <- c("not house1","house","not house2") # name it
as.data.frame(do.call(cbind,TEST[names(TEST)!="house"])) # create data.frame

CodePudding user response:

Here's an option using purrr::map_df() and dplyr::select():

# name                   type              value
# Api_collect            list [5]          List of length 5
#  country               character [1]        US
#  state                 character [1]        Texas
#  computer              character [1]        Mac
#  house                 character [1]        Mansion
#  president             character [1]        Trump

library(dplyr)
library(purrr)

your_list <- list(
    country = "US",
    state = "Texas",
    computer = "Mac",
    house = "Mansion",
    president = "Biden"
)

purrr::map_df(your_list, ~.x) %>% select(-country)

Which gives:

# A tibble: 1 × 4
  state computer house   president
  <chr> <chr>    <chr>   <chr>    
1 Texas Mac      Mansion Biden  
  •  Tags:  
  • r
  • Related