一次创建两个数据框并在 R 中交替连接它们的列

create two dataframes at once and joint their columns alternatively in R

假设这是我的数据框(已经由一系列管道创建)

df <- data.frame(month = c("May", "May","May","June","June","June", "July", "July","July"),
                 rate = rep(c(0.3, 0.4, 0.5),times=3),
                 a = c(5,4,3,10,9,8,20,19,18),
                 b = c(100,200,300,1,2,3,10,20,30))
df

  month rate  a   b
1   May  0.3  5 100
2   May  0.4  4 200
3   May  0.5  3 300
4  June  0.3 10   1
5  June  0.4  9   2
6  June  0.5  8   3
7  July  0.3 20  10
8  July  0.4 19  20
9  July  0.5 18  30

我希望跟随 dplyr 管道并在下面创建数据框:

  month r0.3_a r0.3_b r0.4_a r0.4_b r0.5_a r0.5_b
1   May      5    100      4    200      3    300
2  June     10      1      9      2      8      3
3  July     20     10     19     20     18     30

所以这就是我所做的:

library(tidyverse)
library(dplyr)
library(gtools)
df_a <- df %>%
      select(-b) %>%
      pivot_wider(names_from = rate,
                  values_from = a,
                  names_glue = "r{rate}_{.value}" )

df_b <- df %>%
  select(-a) %>%
  pivot_wider(names_from = rate,
              values_from = b,
              names_glue = "r{rate}_{.value}" )


output <- inner_join(df_a, df_b, by= "month") %>%
          select(month, mixedsort(names(.)[-1]))

我的问题是:假设 df 来自一系列管道,有没有办法在不必停止管道并从原始 df 中创建两个单独的 df 的情况下实现输出?

使用values_from作为列向量

library(tidyr)
library(dplyr)
pivot_wider(df, names_from = rate, values_from = c(a, b),
     names_glue = "r{rate}_{.value}") %>% 
     select(month, gtools::mixedsort(names(.)[-1]))

-输出

# A tibble: 3 × 7
  month r0.3_a r0.3_b r0.4_a r0.4_b r0.5_a r0.5_b
  <chr>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 May        5    100      4    200      3    300
2 June      10      1      9      2      8      3
3 July      20     10     19     20     18     30