答案 0 :(得分:1)
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")