我如何使用 R 和 pivot longer 函数将其正确地安排成两两排列?

How can i properly arrange this in a two by two using R and pivot longer function?

数据集是

structure(list(`total first - yes RS` = 138L, `total first - no RS` = 29L, 
`total second- yes rs` = 6L, `total second- no rs` = 0L), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame"))

看起来像

total first -yes RS|total first -no RS|total second -yes rs|total second -no rs
               76                  20                 12                    0

我想做的是在我有

的地方创建一个两两的
          total first| total second
   Yes rs     76    12
    No rs     20     0

根据输入数据集,分隔符似乎是 space 后跟连字符和列名称中的一些 space。我们可以将 pivot_longer 中的 names_sep 指定为 "\s*-\s*",即零个或多个 space 后跟一个连字符和零个或多个 space。由于列名大小写混合,在整形前最好转为单一大小写

library(dplyr)
library(tidyr)
library(janitor)
df1 %>%
    rename_all(~ toupper(.)) %>%
    pivot_longer(cols = everything(), names_to = c(".value", "grp"), 
         names_sep = "\s*-\s*") %>% 
    column_to_rownames('grp')

这是另一个选项,但具有基本 R 函数 reshape

subset(reshape(
  cbind(q = "",
        setNames(df, tolower(
          gsub("\s?-\s?", ".", names(df))
        ))),
  direction = "long",
  idvar = "q",
  varying = -1
),
select = -c(q, time))

这给出了

        total first total second
.yes rs         138            6
.no rs           29            0