在保持秩序的同时旋转更宽

pivot wider while keeping the order

我有以下数据集

order_id <- c(2,2,2,3,3,3)
product_name <- c("banana","Garlic Powder","carrots","milk","banana","Coconut Butter")


(df <- data.frame(order_id,product_name))


  order_id   product_name
1        2         banana
2        2  Garlic Powder
3        2        carrots
4        3           milk
5        3         banana
6        3 Coconut Butter

我想扩大范围,其中与 order_id 相关的每个产品都是一行。

我使用了以下函数

df%>%
  pivot_wider(names_from =product_name,values_from = product_name)

这给了我这个

  order_id banana `Garlic Powder` carrots milk  `Coconut Butter`
     <dbl> <chr>  <chr>           <chr>   <chr> <chr>           
        2 banana Garlic Powder   carrots NA    NA              
        3 banana NA              NA      milk  Coconut Butter  

但我希望它按照产品在扩大数据集之前的顺序排列,并且我不需要将列名与这些值相关联。我需要这样的东西

   order_id item1     item2         item3
       2    banana  Garlic Powder   carrots                  
       3    milk    banana          Coconut Butter   

我该怎么做?

这是一种解决方案:

library(tidyverse)

order_id <- c(2,2,2,3,3,3)
product_name <- c("banana","Garlic Powder","carrots","milk","banana","Coconut Butter")


df <- data.frame(order_id,product_name) %>% group_by(order_id) %>%
  mutate(id = paste0("item", row_number())) %>%
  pivot_wider(id_cols = order_id,  values_from = product_name, names_from = id)
  

基础 R 解决方案


order_id <- c(2,2,2,3,3,3)
product_name <- c("banana","Garlic Powder","carrots","milk","banana","Coconut Butter")

df <- data.frame(order_id,product_name)

# Create a new variable
df$item <- NA

for(val in unique(df$order_id)){
  df$item[df$order_id==val]<-seq(1,sum(df$order_id==val))
}

# Pivot to wide with base R reshape
reshape(df,
        direction="wide", 
        idvar="order_id", 
        timevar="item")

输出

  order_id product_name.1 product_name.2 product_name.3
1        2         banana  Garlic Powder        carrots
4        3           milk         banana Coconut Butter