我有一个向量列表。此向量由名称A1,A2 ..和数值组成:
a <- list()
a$`p1`["A1"] <- 1
a$`p1`["A2"] <- 0.5
a$`p1`["A3"] <- 0.3
a$`p2`["A3"] <- 2
a$`p2`["A4"] <- 2.5
a$`p2`["A5"] <- 2.3
我希望将其转换为具有以下结构的数据帧
P <- c("p1","p1","p1","p2","p2","p2")
A <- c("A1","A2","A3","A3","A4","A5")
V <- c(1,0.5,0.3,2,2.5,2.3)
out <- data.frame(P,A,V)
谢谢:)
答案 0 :(得分:3)
df_list = lapply(a, function(x) data.frame(A = names(x), V = x, stringsAsFactors = FALSE))
dplyr::bind_rows(df_list, .id = "P")
# P A V
# 1 p1 A1 1.0
# 2 p1 A2 0.5
# 3 p1 A3 0.3
# 4 p2 A3 2.0
# 5 p2 A4 2.5
# 6 p2 A5 2.3
我喜欢上面的方式,但这是一个选项,可能在较大的列表上可能更有效率:
data.frame(V = unlist(a)) %>%
tibble::rownames_to_column() %>%
tidyr::separate(rowname, into = c("P", "A"))
答案 1 :(得分:3)
一个purrr
和tibble
选项可以是:
map_dfr(a, ~ enframe(., name = "A", value = "V"), .id = "P")
P A V
<chr> <chr> <dbl>
1 p1 A1 1
2 p1 A2 0.5
3 p1 A3 0.3
4 p2 A3 2
5 p2 A4 2.5
6 p2 A5 2.3
答案 2 :(得分:2)
在base-R
cbind(stack(a),A=unlist(lapply(a,names),use.names = F))
给予
values ind A
1 1.0 p1 A1
2 0.5 p1 A2
3 0.3 p1 A3
4 2.0 p2 A3
5 2.5 p2 A4
6 2.3 p2 A5
答案 3 :(得分:2)
带有base R
do.call(rbind, Map(cbind, lapply(a, stack), P = names(a)))