【问题标题】:R, pivoting wide to long with extracting prefixes. In tidy wayR,通过提取前缀从宽到长旋转。整齐划一
【发布时间】:2022-01-20 15:27:18
【问题描述】:

我想我正在做的事情几乎与这个问题完全一样:reshape wide to long using prefix as id in R

但如果可能的话,我很想使用 tidyverse。

我有这个数据。这些列是两组几乎相同的变量,前面有一个“pre”或“post”。

data<-structure(list(PreConfidence_NonMarginal = c(3, 1, 2, 4, 4, 5, 
5, 4, 4, 5, 5, 1, 2, 3, 3, 4, 3, 4), PreConfidenceMarginal = c(1, 
1, 1, 3, 3, 4, 4, 4, 4, 4, 2, 1, 1, 1, 2, 3, 2, 1), PreConfidenceInstruments = c(3, 
2, 2, 5, 4, 5, 5, 4, 4, 5, 5, 1, 3, 3, 3, 4, 3, 3), PreConfidenceSutures = c(2, 
1, 2, 4, 2, 5, 3, 4, 4, 4, 5, 1, 2, 2, 3, 4, 3, 3), PreFamiliarAnatomy = c(3, 
3, 2, 5, 3, 4, 4, 4, 4, 5, 4, 1, 2, 3, 3, 3, 2, 3), PreEfficient = c(1, 
1, 1, 3, 3, 3, 3, 4, 3, 4, 5, 1, 1, 1, 4, 3, 2, 3), PostConfidence_NonMarginal = c(4, 
3, 3, 4, 4, 5, 5, 4, 5, 5, 5, 3, 3, 3, 4, 4, 4, 4), PostConfidenceMarginal = c(2, 
2, 2, 4, 4, 4, 4, 4, 5, 4, 3, 3, 1, 3, 4, 3, 3, 3), PostConfidenceInstruments = c(3, 
3, 4, 5, 4, 5, 4, 4, 5, 5, 5, 3, 3, 3, 5, 4, 4, 3), PostConfidenceSutures = c(3, 
3, 4, 4, 3, 5, 3, 5, 5, 4, 5, 3, 3, 3, 5, 4, 3, 3), PostFamiliarAnatomy = c(3, 
4, 2, 5, 3, 4, 4, 4, 4, 5, 4, 3, 3, 3, 4, 4, 3, 4), PostEfficient = c(2, 
2, 2, 4, 3, 4, 4, 5, 3, 4, 5, 3, 2, 3, 4, 4, 2, 4)), row.names = c(NA, 
-18L), class = c("tbl_df", "tbl", "data.frame"))

而且我希望旋转更长的时间,以便列是“pre”和“post”,而变量名的其余部分作为新的行标题。理想情况下,结果应该是这样的:

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    我们可以使用 pivot_longernames_pattern - 捕获前缀部分(PrePost)和其余字符(.*),同时将 names_to 指定为 ".value" 的向量- “问题”列中列的值和列名的后缀部分

    library(dplyr)
    library(tidyr)
    data %>% 
       pivot_longer(cols = everything(), 
       names_to = c(".value", "Question"), names_pattern = "(Pre|Post)(.*)")
    

    -输出

    # A tibble: 108 × 3
       Question                 Pre  Post
       <chr>                  <dbl> <dbl>
     1 Confidence_NonMarginal     3     4
     2 ConfidenceMarginal         1     2
     3 ConfidenceInstruments      3     3
     4 ConfidenceSutures          2     3
     5 FamiliarAnatomy            3     3
     6 Efficient                  1     2
     7 Confidence_NonMarginal     1     3
     8 ConfidenceMarginal         1     2
     9 ConfidenceInstruments      2     3
    10 ConfidenceSutures          1     3
    # … with 98 more rows
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2021-11-10
      • 2021-02-02
      • 1970-01-01
      相关资源
      最近更新 更多