2017-03-06 49 views
1

我在抓取一個網站API,並且遇到問題,將它們的變量以列表形式列表轉換爲數據框中的列。將列表變量列表轉換爲數據框架中的多個變量

我的數據框中的最後一個變量是一個變量,它裏面有很多列表。我如何將這些擴展爲更高級別的數據框中的所有變量?

我的理想輸出可能與下面的列的數據幀:

iddatepatchtournamentstageroundseriesgamemapurlteamis_winnerbans

我最後一欄(df$drafts)包含了我想要的大量數據。我不知道如何將它從列表清單中刪除。

感謝您的任何和所有幫助,請讓我知道如果您需要任何澄清!

library(httr) 

url <- "https://api.masterleague.net/matches" 
data <- GET(url) 
data <- content(data) 
df <- data.frame(t(sapply(data[[4]],c))) 

如果你寧願只用df爲例行工作,這裏是輸出:

df <- structure(list(id = list(2394L), date = list("2017-03-05"), patch = list(18L), tournament = list(38L), stage = list(175L), round = list(
    "Grand Final"), series = list(850L), game = list(5L), map = list(6L), url = list("https://masterleague.net/match/2394/"), drafts = list(list(structure(list(team = 20L, is_winner = TRUE, bans = list(53L, 30L), picks = list(structure(list(hero = 50L,player = 438L), .Names = c("hero", "player")), structure(list(hero = 26L, player = 102L), .Names = c("hero", "player")), structure(list(hero = 52L, player = 104L), .Names = c("hero", "player")), structure(list(hero = 23L, player = 103L), .Names = c("hero", "player")), structure(list(hero = 34L, player = 101L), .Names = c("hero", "player")))), .Names = c("team", "is_winner", "bans", "picks")), structure(list(team = 21L, is_winner = FALSE, bans = list(51L, 35L), picks = list(structure(list(hero = 32L, player = 107L), .Names = c("hero", "player")), structure(list(hero = 47L, player = 108L), .Names = c("hero", "player")), structure(list(hero = 21L, player = 106L), .Names = c("hero", "player")), structure(list(hero = 48L, player = 110L), .Names = c("hero", "player")), structure(list(hero = 20L, player = 105L), .Names = c("hero", "player")))), .Names = c("team", "is_winner", "bans", "picks"))))), .Names = c("id", "date", "patch", "tournament", "stage", "round", "series", "game", "map", "url", "drafts"), row.names = 1L, class = "data.frame") 

使用rbind.data.framedo.call(rbind)sapply我已經失敗嘗試,而且我發現這裏的其他方法在SO上。

回答

1

我覺得這你想要做什麼:

# use lapply to make a list of the unlisted lists (try saying that 10 times fast) 
# within your last column 
drafts <- lapply(seq(nrow(df)), function(i) unlist(df$drafts[i])) 

# collapse that list into a data frame with rows corresponding to the ones in df 
drafts2 <- do.call(rbind, drafts) 

# use cbind to append that new data frame to the original one 
df2 <- cbind(df, drafts2) 

或者,如果你想這樣做在一個鏡頭:

cbind(df, do.call(rbind, lapply(seq(nrow(df)), function(i) unlist(df$drafts[i])))) 
相關問題