如何将我的walkscoreAPI输出列表转换为R中的数据框?

时间:2019-07-25 14:21:17

标签: r csv dataframe rjson

我使用过walkscore API为Lat和Longs列表生成输出

数据集代表:

tibble::tribble(
         ~Lat,        ~Long,
  39.75454546, -82.63637088,
  40.85117794, -81.47034464,
  40.53956136, -74.33630685,
  42.16066679, -71.21368025,
  39.27048579, -119.5770782,
  64.82534285, -147.6738774
  )

我的代码:

library(walkscoreAPI)
library(rjson)
data = read.csv(file="geocode_finalcompiled.csv", header=TRUE, sep=",")
attach(data)
#create empty list
res = list()
# for loop through a file

for(i in 1:500){
  res[i] = list(getWS(data$Long[i],data$Lat[i],"mykey"))

}

显示结果

res

> res
[[1]]
$status
[1] 1

$walkscore
[1] 2

$description
[1] "Car-Dependent"

$updated
[1] "2019-03-28 21:43:37.670012"

$snappedLong
[1] -82.6365

$snappedLat
[1] 39.7545

您可以看到输出为json格式。我的目标是使其成为一个数据框,其中每个值都显示在每个标题下,并且可以放入csv中。

我尝试过:

  

重新格式化的<-as.data.frame(res)

但是出现以下错误:

as.data.frame.default(x [[i]],可选= TRUE,stringsAsFactors = stringsAsFactors)中的错误:   无法将“ WalkScore”类强制转换为data.frame

该如何解决?

1 个答案:

答案 0 :(得分:1)

采用上述方法:

library(dplyr)
library(tibble)

res %>% 
  sapply(unclass) %>% 
  as.data.frame() %>% 
  t() %>% 
  as.data.frame() %>% 
  lapply(unlist) %>% 
  as.data.frame(stringsAsFactors = FALSE) %>% 
  remove_rownames() -> df

产生:

#   status walkscore       description                    updated snappedLong snappedLat
# 1      1         2     Car-Dependent 2019-03-28 21:43:37.670012    -82.6365    39.7545
# 2      1         4     Car-Dependent 2019-04-11 11:23:51.651955     -81.471     40.851
# 3      1        60 Somewhat Walkable 2019-02-25 01:05:08.918498     -74.337     40.539
# 4      1        44     Car-Dependent 2019-04-17 16:26:58.848496     -71.214    42.1605
# 5      1        16     Car-Dependent 2019-05-09 01:34:59.741290    -119.577      39.27
# 6      1         0     Car-Dependent 2019-07-22 19:27:50.170107   -147.6735    64.8255

并使用以下命令写入csv:

write.csv(df, file = "dfwalk.csv")