簡體   English   中英

R 在數據框中提取列表

[英]R extracting lists within dataframes

解析嵌入在數據框中變量中的列表的最佳方法是什么?

在 R 中解析 json 時(我通常使用 jsonlite 包),我經常最終得到包含列表(其他列表或數據框的)的數據框列。 一個簡單的例子是解析 Twitter 流數據,其中坐標作為緯度和經度列表返回。 一個更復雜的例子(也是我目前正在處理的那個)是醫生的 JSON,它將地址解析為數據幀列表。 這是一些說明結構的示例數據(順便說一下,這是公共數據):

> str(df)
Classes ‘tbl_df’ and 'data.frame':  2 obs. of  2 variables:
 $ addresses:List of 2
  ..$ :'data.frame':    1 obs. of  6 variables:
  .. ..$ address  : chr "Department of Palliative Care"
  .. ..$ address_2: chr "2525 Cumberland Parkway, SE"
  .. ..$ city     : chr "Atlanta"
  .. ..$ state    : chr "GA"
  .. ..$ zip      : chr "30305"
  .. ..$ phone    : chr "4043650966"
  ..$ :'data.frame':    2 obs. of  6 variables:
  .. ..$ address  : chr  "5445 Meridian Mark Road" "3619 South Fulton Avenue"
  .. ..$ address_2: chr  "Suite 370" ""
  .. ..$ city     : chr  "Atlanta" "Hapeville"
  .. ..$ state    : chr  "GA" "GA"
  .. ..$ zip      : chr  "30342" "30354"
  .. ..$ phone    : chr  "4047652020" "4047652020"
 $ npi      : chr  "1497831390" "1578667986"

jsonlite 有一個函數 (flatten) 用於將嵌入的數據幀提取到單個變量,但它不適用於列表。

在 Twitter 示例中,我可以使用 for 循環將列表項提取到同一數據幀中的變量:

for (i in 1:nrow(df)){
  #sometimes coordinates is blank, so check
  if (length(df2$coordinates.coordinates[[i]]>0)){
    df2[i,"coordinates.lon"]<- df2$coordinates.coordinates[[i]][1]
    df2[i,"coordinates.lat"]<- df2$coordinates.coordinates[[i]][2]
  }

在 Doctor 示例中,由於每個 Doctor 可以有多個地址,因此我需要創建一個新數據集。

library(dplyr)
addresses = data.frame()
for (i in 1:nrow(df)){
  x<-df$addresses[[i]]
  #need an identifier
  x$id <-df[[i,"npi"]]
  addresses <-bind_rows(addresses, x)
}

雖然這兩個例子都有效,但它們都 a) 緩慢且 b) 不是“R”的做事方式(據我所知)。

所以,我的問題是:從數據框變量中提取列表的更好、更快、更“R”的方法是什么?

感謝理查德·斯克里文。 unnest in tidr正是我所需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM