[英]R - convert named list of named vectors into dataframe where one vector is placed in one cell
我有一個命名向量的命名列表:
my_list <- list('first'=c('foo_1'=7, 'bar_1'=3), 'second'=c('foo_2'=4, 'bar_2'=2, 'baz'=1))
我想將其轉換為數據框,其中列表元素的名稱應為數據框索引,命名向量應為數據框單元格值。 諸如此類(或my_vectors
列中的任何類似內容):
my_vectors
first 'foo_1'=7, 'bar_1'=3
second 'foo_2'=4, 'bar_2'=2, 'baz'=1
我怎樣才能做到這一點?
謝謝!
我不確定為什么要這樣做,但是如果您確實需要,可以采用以下一種方法:
library(dplyr)
library(tidyr)
# convert lists to data frame
unlisted <- unlist(my_list) %>% data.frame
# majority of data transformation
unlisted <- mutate(unlisted, variable = rownames(unlisted), value = `.`) %>%
separate(variable, c('vector', 'item'), sep = '\\.') %>%
group_by(vector) %>%
summarize(my_vectors = paste(sprintf('%s = %i', item, value), collapse = ', ')) %>%
data.frame
# remove superfluous "vector" column and move those values to row indices
rownames(unlisted) <- unlisted$vector
unlisted$vector <- NULL
結果:
my_vectors
first foo_1 = 7, bar_1 = 3
second foo_2 = 4, bar_2 = 2, baz = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.