簡體   English   中英

與數據框R具有不同長度和類型的子列表列表

[英]List of sublists with different lengths and types to dataframe R

我有一個列表列表list_of_lists

理論上,每個sub_list的長度都可以不同,例如:

list_of_lists[[1]]
$id = 1
$variable1 = "8"
$variable2 = 8  12.2

和...

list_of_lists[[2]]
$id = 2
$variable1 = "4"
$variable2 = 2  2.2  12.1 200.1

我想將list_of_lists轉換為長數據框。 看過這個SO帖子

b = as.data.frame(matrix(unlist(list_of_lists), nrow=length(unlist(list_of_lists[1]))))

並嘗試了這個:

long_df = ldply(list_of_lists, as.data.frame)

兩者都不如我預期的那樣工作。

我想要一個長df,例如:

id    variable1    variable2
1     "8"          8
1     "8"          12.2
2     "4"          2
2     "4"          2.2
2     "4"          12.1
2     "4"          200.1

將每個子列表分別轉換為數據幀,然后假定所有子列表具有相同的字段,則對它們進行rbind

do.call(rbind, lapply(list_of_lists, data.frame))

#   id var1  var2
# 1  1    8   8.0
# 2  1    8  12.2
# 3  2    4   2.0
# 4  2    4   2.2
# 5  2    4  12.1
# 6  2    4 200.1

暫無
暫無

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

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