首页 > 解决方案 > 我怎样才能转动这个小标题?

问题描述

考虑到这个小标题

library(tibble)
mytab <- tribble(
  ~siren_ent, ~nbeta_dep01, ~nbeta_dep02, ~effeta_dep01, ~effeta_dep02, ~categ, 
  "A",   3,   0,   50,   0,   "X",
  "B",   0,   2,    0,  30,   "X",
  "C",   1,   1,  10,   15,   "Y"
)

我想转动它以获得这个结果......

> result
# A tibble: 4 x 4
  DEP   categ nbeta effeta
  <chr> <chr> <dbl>  <dbl>
1 01    X         3     50
2 01    X         1     10
3 02    Y         2     30
4 02    Y         1     15

如果您有 tidyverse 的解决方案,我很感兴趣。

提前谢谢了 !

标签: rtidyverse

解决方案


我假设您的第二个effeta_dep01专栏实际上应该被称为effeta_dep02. 如果是这样,那么这给出了接近所需输出的东西:

library(tidyr)
library(dplyr)

mytab %>%
  pivot_longer(nbeta_dep01:effeta_dep02,
               names_sep = "_dep",
               names_to = c(".value", "dep")) %>% 
  filter(nbeta > 0) %>% 
  select(-siren_ent)

这使

# A tibble: 4 x 4
  categ dep   nbeta effeta
  <chr> <chr> <dbl>  <dbl>
1 X     01        3     50
2 X     02        2     30
3 Y     01        1     10
4 Y     02        1     15

我假设您的预期输出不正确,但如果不是,我很高兴知道您期望的转换。


推荐阅读