在 R 中使用两个列因子重新排序数据框

Reorder dataframe with two column factors in R

我有这个数据框,我们可以在列名中看到每个观察值所属的因素。

我想得到一个新的数据框,重新排序之前的数据框,如下所示:

我尝试使用 reshape 包,但缺少一些东西。有人吗?

tidyverse 的一个选项是将 gather 列转换为 'long',然后 separate 将 'key' 列转换为两列并执行 arrange

library(tidyverse)
rownames_to_column(Dataset, 'rn') %>% 
    gather(key, Count, -rn) %>% 
    separate(key, into = c('Factor_1', 'Factor_2')) %>% 
    arrange(Factor_1, rn) %>%
    select(Count, Factor_1, Factor_2)
#   Count Factor_1 Factor_2
#1      1        A        X
#2      4        A        Y
#3      2        A        X
#4      3        A        Y
#5      5        B        X
#6      8        B        Y
#7      6        B        X
#8      7        B        Y
#9      9        C        X
#10    12        C        Y
#11    10        C        X
#12    11        C        Y

base R

res <- do.call(rbind, lapply(split.default(Dataset, sub("_.*", "", names(Dataset))), 
    function(x) data.frame(Count = c(t(x)), 
    read.table(text = rep(names(x), nrow(x)), header = FALSE, sep="_"))))
row.names(res) <- NULL

数据

Dataset <- structure(list(A_X = 1:2, A_Y = c(4L, 3L), B_X = 5:6, B_Y = c(8L, 
7L), C_X = 9:10, C_Y = c(12L, 11L)), .Names = c("A_X", "A_Y", 
"B_X", "B_Y", "C_X", "C_Y"), row.names = c(NA, -2L), class = "data.frame")