JMQ*_*JMQ 2 r list dataframe google-places-api googleway
我正在尝试存储我通过 Google Places API 从列表中检索到的数据框的结果。我对 API 的调用...
library(googleway)
HAVE_PLACES <- google_places(search_string = "grocery store",
location = c(35.4168, -80.5883),
radius = 10000, key = key)
Run Code Online (Sandbox Code Playgroud)
...返回一个列表对象HAVE_PLACES
:
此列表中的第三个对象 - results
- 是一个数据框,对 API 调用中检索到的每个位置都有一个观察结果。当我打电话时View(HAVE_PLACES$results)
,我得到了一组向量 - 正如我在查看数据框时所期望的那样......
...但看起来数据框包含数据框:
这里发生了什么?
进一步来说:
View()
将嵌套数据框显示为向量?View()
只是向量 - 用于操作和导出目的 - 是否有任何最佳实践?我即将把这个所谓的数据帧的每个向量转换geometry
成单独的对象,并将cbind()
结果转换为HAVE_PLACES$results
. 但这感觉很疯狂。阿克伦是对的(像往常一样!)。data.frame 可以将列表作为“列”。这是正常行为。
您的问题似乎是关于如何在 R 中提取嵌套列表数据的更笼统的问题,但以 Google 的 API 响应为例。鉴于您正在使用googleway
(我是 pacakge 的作者),我将在 Google 的回复中进行回答。但是,关于如何在 R 中使用列表,网上还有许多其他答案和示例。
您会在结果中看到嵌套列表,因为从 Google 的 API 返回的数据实际上是 JSON。该google_places()
函数将其“简化”为内部data.frame
使用jsonlite::fromJSON()
。
如果您simplify = F
在函数调用中设置,您可以看到原始 JSON 输出
library(googleway)
set_key("GOOGLE_API_KEY")
HAVE_PLACES_JSON <- google_places(search_string = "grocery store",
location = c(35.4168, -80.5883),
radius = 10000,
simplify = F)
## run this to view the JSON.
jsonlite::prettify(paste0(HAVE_PLACES_JSON))
Run Code Online (Sandbox Code Playgroud)
您将看到 JSON 可以包含许多嵌套对象。当转换为 R 时,data.frame
这些嵌套对象将作为列表列返回
如果您不熟悉 JSON,可能值得进行一些研究以了解它的全部内容。
我已经编写了一些函数来从 API 响应中提取有用的信息,这可能对这里有帮助
locations <- place_location(HAVE_PLACES)
head(locations)
# lat lng
# 1 35.38690 -80.55993
# 2 35.42111 -80.57277
# 3 35.37006 -80.66360
# 4 35.39793 -80.60813
# 5 35.44328 -80.62367
# 6 35.37034 -80.54748
placenames <- place_name(HAVE_PLACES)
head(placenames)
# "Food Lion" "Food Lion" "Food Lion" "Food Lion" "Food Lion" "Food Lion"
Run Code Online (Sandbox Code Playgroud)
但是,请注意,您仍然会返回一些列表对象,因为在这种情况下,“位置”可以有许多“类型”
placetypes <- place_type(HAVE_PLACES)
str(placetypes)
# List of 20
# $ : chr [1:5] "grocery_or_supermarket" "store" "food" "point_of_interest" ...
# $ : chr [1:5] "grocery_or_supermarket" "store" "food" "point_of_interest" ...
# $ : chr [1:5] "grocery_or_supermarket" "store" "food" "point_of_interest" ...
# $ : chr [1:5] "grocery_or_supermarket" "store" "food" "point_of_interest" ...
Run Code Online (Sandbox Code Playgroud)
使用 Google 的 API 响应,您必须提取所需的特定数据元素并将它们构建到所需的对象中
df <- cbind(
place_name(HAVE_PLACES)
, place_location(HAVE_PLACES)
, place_type(HAVE_PLACES)[[1]] ## only selecting the 1st 'type'
)
head(df)
# place_name(HAVE_PLACES) lat lng place_type(HAVE_PLACES)[[1]]
# 1 Food Lion 35.38690 -80.55993 grocery_or_supermarket
# 2 Food Lion 35.42111 -80.57277 store
# 3 Food Lion 35.37006 -80.66360 food
# 4 Food Lion 35.39793 -80.60813 point_of_interest
# 5 Food Lion 35.44328 -80.62367 establishment
# 6 Food Lion 35.37034 -80.54748 grocery_or_supermarket
Run Code Online (Sandbox Code Playgroud)