【问题标题】:How do I convert my walkscoreAPI output list to a dataframe in R?如何将 walkscoreAPI 输出列表转换为 R 中的数据框?
【发布时间】:2019-12-03 20:46:26
【问题描述】:

我已使用 walkscore API 为经纬度列表生成输出

数据集的表示:

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
[[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.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) 中的错误: 无法将“WalkScore”类强制转换为 data.frame

有什么办法可以解决这个问题?

【问题讨论】:

  • 输出是list 而不是json 还是我错了?取消分类并根据需要将其设为 df。
  • @NelsonGon 你如何取消分类并使其成为 df?
  • 无法测试,因为我没有安装这个包。试试as.data.frame(unclass(res))。或者,sapply(res, class) 的输出是什么?
  • > sapply(res, class) [1] "WalkScore" "WalkScore" "WalkScore" "WalkScore" "WalkScore" "WalkScore"
  • 是的,我放在这里的代表是我的数据集的表示

标签: r csv dataframe rjson


【解决方案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")

【讨论】:

  • 嗨,马修,这行得通。这听起来像是一个基本问题,但是当我尝试将此脚本分配给向量并写入 csv 时,我得到一个错误 > write.csv(df, file = "dfwalk.csv") Error in write.table(df, file = "dfwalk.csv", col.names = NA, sep = ",", : 'EncodeElement' 中未实现的类型'list'。如何将其写入 csv?
  • 见上面的编辑。显然旧代码没有生成正确的 data.frame,即使它在使用 print 方法查看时看起来很像。几乎可以肯定有更好的方法可以做到这一点,但上述方法有效。
  • 查看更明确的关于写入 csv 的重新编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2021-11-21
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多