我如何使用 R 和 Pivot Long 函数将其正确地排列成两个两个? [英] How can i properly arrange this in a two by two using R and pivot longer function?

查看:92
本文介绍了我如何使用 R 和 Pivot Long 函数将其正确地排列成两个两个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据集是

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

我想做的是在我有的地方创建一个两个两个

What i would like to do is create a two by two where I have

          total first| total second
   Yes rs     76    12
    No rs     20     0

推荐答案

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

Based on the input dataset, the delimiter seems to be space followed by a hyphen and some space in the column names. We can specify the names_sep in pivot_longer as "\\s*-\\s*" i.e. zero or more spaces followed by a hyphen and zero or more spaces. As the column names have lower and upper cases mixed, it is better to convert to a single case before doing the reshaping

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 和 Pivot Long 函数将其正确地排列成两个两个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆