重新排序列表中的数据帧

时间:2018-04-11 20:38:10

标签: r

我使用以下代码创建了10个数据框的列表:

lst <- setNames(replicate(10, sample(1:nrow(CatW),7, replace=FALSE), simplify = FALSE), 1:10)

sampled_W <- lapply(seq_along(lst), function(i) transform(CatW[lst[[i]], ], ind = i))

给我这个总结:

     Length Class      Mode  
[1,] 11     data.frame list  
[2,] 11     data.frame list  
[3,] 11     data.frame list  
[4,] 11     data.frame list  
[5,] 11     data.frame list  
[6,] 11     data.frame list  
[7,] 11     data.frame list  
[8,] 11     data.frame list  
[9,] 11     data.frame list  
[10,] 11    data.frame list

我想提取数据,以便我可以使用它来运行模型,但我需要将每个data.frame中的列堆叠成行来执行此操作,即我想更改输出:

Variable 1 variable 2 variable 3 
x           y           z

为:

Variable  Type
x          1
y          2
z          3

我不能操纵我的个人数据帧,因为它们是列表的一部分,samples_W。我该如何解决这个问题?

谢谢

1 个答案:

答案 0 :(得分:0)

我们可以gather data.frame内的list到{&#39;长&#39;格式

library(tidyverse)
map(sampled_W, ~ .x %>%
                  gather(key, Variable) %>% 
                  separate(key, into = c("key1", "Type"), convert = TRUE) %>% 
                  select(Variable, Type))# %>%
   #if needed to bind the rows and create a single dataset
   #bind_rows(.id = 'grp')
#[[1]]
#  Variable Type
#1        x    1
#2        y    2
#3        z    3

#[[2]]
#  Variable Type
#1        x    1
#2        y    2
#3        z    3

数据

sampled_W  <- list(structure(list(`Variable 1` = "x", `Variable 2` = "y",
   `Variable 3` = "z"), .Names = c("Variable 1", 
"Variable 2", "Variable 3"), class = "data.frame", row.names = c(NA, 
 -1L)), structure(list(`Variable 1` = "x", `Variable 2` = "y", 
`Variable 3` = "z"), .Names = c("Variable 1", "Variable 2", 
 "Variable 3"), class = "data.frame", row.names = c(NA, -1L)))