Search code examples
rdataframeflattengoogleway

Flatten or unlist a data frame in R


I am using the Googleway package to get the elevation information for a bunch of lat long coordinates of which there are 954 in total.

I've broken the calls into 3 separate files but they're in list format and when I convert them to a dataframe they are in nested dataframe formats. I've been trying to flatten the files and unlist them but I am having no success.

DF <- read.csv("Site Coor R.csv", header = T, colClasses = c("numeric","numeric"))

result1 <- google_elevation(df_locations = DF[1:350,], key = "KEY")
result2 <- google_elevation(df_locations = DF[351:700,], key = "KEY")
result3 <- google_elevation(df_locations = DF[701:954,], key = "KEY")

> str(result1)
List of 2
 $ results:'data.frame':    350 obs. of  3 variables:
  ..$ elevation : num [1:350] 14.15 2.14 2.66 6.78 23.27 ...
  ..$ location  :'data.frame':  350 obs. of  2 variables:
  .. ..$ lat: num [1:350] 52.7 52.7 52.7 52.9 52.7 ...
  .. ..$ lng: num [1:350] -8.61 -8.83 -8.92 -8.98 -8.91 ...
  ..$ resolution: num [1:350] 611 611 611 611 611 ...
 $ status : chr "OK"


do.call("c", result1[["location"]])

or

result1 <- unlist(result1, recursive = TRUE, use.names = TRUE)

or

write.table(data.frame(subset(result1DF,select=-c(results.location)),unclass(result1DF$results.location)))

Since result1, result2 and result3 are of the same structure is there a simple way to merge them, flatten the conjoined table and then export as CSV?


Solution

  • We can get all the objects in a list and create data.frame in a single call

    lst <- lapply(mget(paste0("result", 1:3)), function(x) do.call(data.frame, x$results))
    str(lst[[1]])
    #'data.frame':   12 obs. of  3 variables:
    #$ elevation   : num  -0.546 0.537 0.42 -0.584 0.847 ...
    #$ location.lat: int  61 85 53 80 82 52 66 62 68 57 ...
    #$ location.lng: int  11 7 10 19 1 -2 -6 -8 -14 -13 ...
    

    If we need a single table, then rbind them together

    library(data.table)
    dt <- rbindlist(lst)
    fwrite(dt, file = "yourfile.csv")
    

    data

    f1 <- function(seed){
         set.seed(seed)
         results <- data.frame(elevation = rnorm(12))
         results$location <- data.frame(lat = sample(50:100, 12, replace=TRUE), 
               lng = sample(-15:20, 12, replace=TRUE))
          results
      }
    
    result1 <- list(results = f1(24), status = "OK")
    result2 <- list(results = f1(42), status = "OK")
    result3 <- list(results = f1(343), status = "OK")