我在 R 中有一个复杂的列表结构,我想将其放入数据帧格式中。数据如下。该列表包含五个不同音乐专辑的八列数据。每个列表元素中的行数等于为专辑做出贡献的人员数量,这是我的主要兴趣。
将列表转换为具有 12 行和 8 列的数据框的有效方法是什么?理想情况下,我想创建一个函数,它接受一个参数(具有相同 8 列的任意数量的音乐专辑的列表)并返回一个数据帧。
我尝试过使用flatten
,unnest
并map
以各种方式,但无法破解这个。
df2<-list(NULL, structure(list(join = c(\"/\", \"/\", \"/\", \"/\", \"/\", \"\"\r\n), name = c(\"Art Tatum\", \"Lionel Hampton\", \"Harry Edison\", \"Buddy Rich\", \r\n\"Red Callender\", \"Barney Kessel\"), anv = c(\"\", \"\", \"\", \"\", \"\", \r\n\"\"), tracks = c(\"\", \"\", \"\", \"\", \"\", \"\"), role = c(\"\", \"\", \"\", \r\n\"\", \"\", \"\"), resource_url = c(\"https://api.discogs.com/artists/265634\", \r\n\"https://api.discogs.com/artists/136133\", \"https://api.discogs.com/artists/258469\", \r\n\"https://api.discogs.com/artists/57620\", \"https://api.discogs.com/artists/272014\", \r\n\"https://api.discogs.com/artists/253476\"), id = c(265634L, 136133L, \r\n258469L, 57620L, 272014L, 253476L), `frset$title` = c(\"The Tatum Group Masterpieces, Vol. 5\", \r\n\"The Tatum Group Masterpieces, Vol. 5\", \"The Tatum Group Masterpieces, Vol. 5\", \r\n\"The Tatum Group Masterpieces, Vol. 5\", \"The Tatum Group Masterpieces, Vol. 5\", \r\n\"The Tatum Group Masterpieces, Vol. 5\")), class = \"data.frame\", row.names = c(NA, \r\n6L)), structure(list(join = \"\", name = \"Art Tatum\", anv = \"\", \r\n tracks = \"\", role = \"\", resource_url = \"https://api.discogs.com/artists/265634\", \r\n id = 265634L, `frset$title` = \"This Is...Art Tatum - Vol 1\"), class = \"data.frame\", row.names = 1L), \r\n structure(list(join = c(\"/\", \"/\", \"\"), name = c(\"Oscar Peterson\", \r\n \"Erroll Garner\", \"Art Tatum\"), anv = c(\"\", \"\", \"\"), tracks = c(\"\", \r\n \"\", \"\"), role = c(\"\", \"\", \"\"), resource_url = c(\"https://api.discogs.com/artists/254394\", \r\n \"https://api.discogs.com/artists/262816\", \"https://api.discogs.com/artists/265634\"\r\n ), id = c(254394L, 262816L, 265634L), `frset$title` = c(\"Great Jazz Pianists\", \r\n \"Great Jazz Pianists\", \"Great Jazz Pianists\")), class = \"data.frame\", row.names = c(NA, \r\n 3L)), structure(list(join = \"\", name = \"Art Tatum\", anv = \"\", \r\n tracks = \"\", role = \"\", resource_url = \"https://api.discogs.com/artists/265634\", \r\n id = 265634L, `frset$title` = \"Art Tatum\"), class = \"data.frame\", row.names = 1L), \r\n structure(list(join = \"\", name = \"Art Tatum\", anv = \"\", tracks = \"\", \r\n role = \"\", resource_url = \"https://api.discogs.com/artists/265634\", \r\n id = 265634L, `frset$title` = \"Art!\"), class = \"data.frame\", row.names = 1L))
df2<-unlist(lapply(df, function(x) if (length(x)==8) list(x) else x), recursive=FALSE) # remove NULL lists or those with wrong dimensions
albumdata<-list()
personnel<-function(df){
for(i in 1:length(df))
albumdata[[i]]<-as.data.frame(unlist(df[i+1],recursive=FALSE))
return(albumdata)
message("Album #",dim(albumdata[[2]])[1])
}
该函数再次返回一个列表。为什么?