R – 似乎无法使用pivot_longer重新组织数据集

问题描述 投票:0回答:1

我有以下数据框:

受控 不受控制 SE_受控 SE_不受控制
a c e g
女人 b d f h

但是,我发现这种布局没有帮助,我希望具有以下结构:

控制 道具 SE
受控 a e
女人 受控 b f
不受控制 c g
女人 不受控制 d h

我尝试过使用pivot_longer(),但似乎找不到正确的解决方案。有什么建议吗?

r data-structures pivot tidyverse
1个回答
0
投票
library(tidyverse)

df |>
  rename_with(~ paste0("temp_", .x), .cols = c(Controlled, Uncontrolled)) |>
  pivot_longer(-Sex, names_to = c(".value", "type"), names_sep = "_")

输出:

# A tibble: 4 × 4
  Sex   type         temp  SE   
  <chr> <chr>        <chr> <chr>
1 Male  Controlled   a     e    
2 Male  Uncontrolled c     g    
3 Woman Controlled   b     f    
4 Woman Uncontrolled d     h    

数据:

df <- read.table(text="
Sex     Controlled  Uncontrolled    SE_Controlled   SE_Uncontrolled
Male    a   c   e   g
Woman   b   d   f   h", head = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.