首页 > 解决方案 > 如何使用 R 和旋转更长的功能将其正确排列成两两?

问题描述

数据集是

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

标签: rpivot

解决方案


这是另一种选择,但具有基本 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

推荐阅读