与成对比较的pivot_longer

时间:2019-12-16 10:00:18

标签: r tidyverse

我有以下数据框

> data <- 
structure(list(a = 1:2, b = c(2L, 2L), c = 1:2, d = c(1L, 4L)), row.names = c("a", 
"b"), class = "data.frame")

> data
  a b c d
a 1 2 1 1
b 2 2 2 4

我想使用tidyverse的ivot_longer以长格式进行所有成对比较

结果应该像这样

compA  compB    value
     a      a      1
     a      b      2
     b      a      2
     b      b      2
     c      a      1
     c      b      2
     d      a      1
     d      b      4

我尝试过:

   data %>% pivot_longer(cols=everything(),names_to=c("compA","compB"),values_to="value")

Error: If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.

如何使用tidyverse shaft_longer获得所需的输出? 谢谢

1 个答案:

答案 0 :(得分:0)

将行名添加为列,然后使用pivot_longer

library(tibble)
library(tidyr)

data %>%  rownames_to_column('row') %>% pivot_longer(cols = -row)

#  row   name  value
#  <chr> <chr> <int>
#1 a     a         1
#2 a     b         2
#3 a     c         1
#4 a     d         1
#5 b     a         2
#6 b     b         2
#7 b     c         2
#8 b     d         4