The*_*oat 2 r flatten dataframe googleway
我正在使用该Googleway
软件包获取一堆lat长坐标的高程信息,其总共有954个.
我将调用分成3个单独的文件,但它们是列表格式,当我将它们转换为数据帧时,它们是嵌套的数据帧格式.我一直试图压扁文件并取消列出,但我没有成功.
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"]])
Run Code Online (Sandbox Code Playgroud)
要么
result1 <- unlist(result1, recursive = TRUE, use.names = TRUE)
Run Code Online (Sandbox Code Playgroud)
要么
write.table(data.frame(subset(result1DF,select=-c(results.location)),unclass(result1DF$results.location)))
Run Code Online (Sandbox Code Playgroud)
既然result1
,result2
并且result3
具有相同的结构,有一种简单的方法来合并它们,展平连接表然后导出为CSV?
我们可以获取a中的所有对象list
并data.frame
在单个调用中创建
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 ...
Run Code Online (Sandbox Code Playgroud)
如果我们需要一个表,那么rbind
它们在一起
library(data.table)
dt <- rbindlist(lst)
fwrite(dt, file = "yourfile.csv")
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)