如何将列表列表提取到单个数据框中(最好按名称引用)?

时间:2018-11-09 13:36:15

标签: r list

我有一个列表列表:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'myChannel' cannot be found on object of type 'org.springframework.messaging.support.GenericMessage' - maybe not public or not valid?

结构如下:

> dput(results)
list(list(type = "sales", value = 9L, all_time_value = 833L), 
    list(type = "gmv", value = 3644.21716861478, all_time_value = 344375.321075978), 
    list(type = "aov", value = 404.913018734976, all_time_value = 413.415751591811), 
    list(type = "acr", value = 0.108433734939759, all_time_value = 0.149283154121864), 
    list(type = "initiated-chats", value = 89L, all_time_value = 10299L), 
    list(type = "chats-claimed", value = 82L, all_time_value = 5497L), 
    list(type = "chats-per-available-user", value = 3.15384615384615, 
        all_time_value = 57.2604166666667), list(type = "rating", 
        value = 5L, all_time_value = 4.58640776699029))

此列表是从后端系统中提取的,将始终包含相同的指标,但是这些值可能并不总是以该特定顺序出现。

我想将每个列表的元素提取到一个由三行(> library(dplyr) > results %>% str List of 8 $ :List of 3 ..$ type : chr "sales" ..$ value : int 9 ..$ all_time_value: int 833 $ :List of 3 ..$ type : chr "gmv" ..$ value : num 3644 ..$ all_time_value: num 344375 $ :List of 3 ..$ type : chr "aov" ..$ value : num 405 ..$ all_time_value: num 413 $ :List of 3 ..$ type : chr "acr" ..$ value : num 0.108 ..$ all_time_value: num 0.149 $ :List of 3 ..$ type : chr "initiated-chats" ..$ value : int 89 ..$ all_time_value: int 10299 $ :List of 3 ..$ type : chr "chats-claimed" ..$ value : int 82 ..$ all_time_value: int 5497 $ :List of 3 ..$ type : chr "chats-per-available-user" ..$ value : num 3.15 ..$ all_time_value: num 57.3 $ :List of 3 ..$ type : chr "rating" ..$ value : int 5 ..$ all_time_value: num 4.59 typevalue)和八列组成的单个数据框中,每列根据all_time_value中的相应值。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

首先将整个内容压成data.frame

df <- do.call("rbind.data.frame", lapply(results, as.data.frame))

然后将其翻转

t(df)

多合一方法:

df <- t(do.call("rbind.data.frame", lapply(results, as.data.frame)))

答案 1 :(得分:0)

rbindlist可能更有效,请尝试data.frame(t(data.table::rbindlist(results)))

# or with the columns name
df <- data.frame(t(data.table::rbindlist(results)))
df <- setNames(df[-1, ], sapply(df[1, ], as.character))

# output
                      sales          gmv          aov          acr initiated-chats chats-claimed chats-per-available-user       rating
value             9.0000000 3644.2171686  404.9130187    0.1084337      89.0000000    82.0000000                3.1538462    5.0000000
all_time_value 8.330000e+02 3.443753e+05 4.134158e+02 1.492832e-01    1.029900e+04  5.497000e+03  

       5.726042e+01 4.586408e+00