基于R中数据框中的列旋转数据框/自连接

Pivoting dataframe / self joining based on column within dataframe in R

我有这个数据框:

df <- data.frame(
  item_number = c(1, 1, 1, 2, 2, 2),
  scales = c(1, 5, 10, 2, 15, 20),
  prices = c(1, 1.50, 2, 3, 4, 5),
  product_name = c("Cheese", "Cheese", "Cheese", "Ham", "Ham", "Ham")
  )
  item_number scales prices product_name
1           1      1    1.0       Cheese
2           1      5    1.5       Cheese
3           1     10    2.0       Cheese
4           2      2    3.0          Ham
5           2     15    4.0          Ham
6           2     20    5.0          Ham

我想要这个数据框:

  item_number scale_1 scale_2 scale_3 price_1 price_2 price_3 product_name
1           1       1       5      10       1     1.5       2       Cheese
2           2       2      15      20       3     4.0       5          Ham

我已经尝试过 pivot wider dplyr 函数和自连接,但不确定如何获得所需的解决方案

library(tidyverse)
df %>%
  group_by(item_number) %>%
  mutate(row = row_number()) %>%
  ungroup() %>%
  pivot_wider(names_from = row, values_from = c(scales, prices))

结果

# A tibble: 2 × 8
  item_number product_name scales_1 scales_2 scales_3 prices_1 prices_2 prices_3
        <dbl> <chr>           <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
1           1 Cheese              1        5       10        1      1.5        2
2           2 Ham                 2       15       20        3      4          5