我需要从列表中挖掘出类似的数据帧并将它们放入数据帧中。我创建了一个玩具示例:
nn <- list()
h <- data.frame(a = c(5,6), j = c(8,1), g = c("d","o"))
rnz <- c("test1","test2")
o <- data.frame(a = c(1,2), j = c(6,4), g = c("r","u"))
rownames(h) <- rnz
rownames(o) <- rnz
i <- 1:4
nn$set1 <- list(num = i, df = h)
nn$set2 <- list(num = i / 2, df = o)
现在我想将列表提取为以下整洁格式
var a j
set1 test1 5 8
set1 test2 6 1
set2 test1 1 6
set2 test2 2 4
但是 - 当我做的时候
df <- lapply(nn, function(x) x$df[ , c(1,2)])
df2 <- lapply(df, function(x) tibble::rownames_to_column(x, "var"))
df3 <- do.call(rbind, lapply(df2, function(c) as.data.frame(c, row.names = NULL)))
我明白了:
var a j
set1.1 test1 5 8
set1.2 test2 6 1
set2.1 test1 1 6
set2.2 test2 2 4
如何删除删除行列中的.1,.2等?有没有更简洁的方法呢?
答案 0 :(得分:5)
dplyr::bind_rows
有一个.id
参数可以将元素名称强制转换为列。 purrr::map_df
将其封装,包括.id
参数,因此您可以直接从nn
转换:
library(purrr)
# extract data.frame elements
nn %>% map('df') %>%
# add rownames to each data.frame; coerce result to data.frame with element names as column
map_df(tibble::rownames_to_column, 'var', .id = 'name')
## name var a j g
## 1 set1 test1 5 8 d
## 2 set1 test2 6 1 o
## 3 set2 test1 1 6 r
## 4 set2 test2 2 4 u
答案 1 :(得分:3)
我们可以将rbindlist
与idcol
参数
library(data.table)
rbindlist(lapply(nn, function(x) transform( x$df[1:2],
var = row.names(x$df))), idcol = "name")
# name a j var
#1: set1 5 8 test1
#2: set1 6 1 test2
#3: set2 1 6 test1
#4: set2 2 4 test2