Phần I

Đây là bảng Tính tổng doanh thu của các kênh bán: Distributor, In-Store, Online, Wholesale và theo các tháng từ 07/2018 - 12/2020:

C1: Dùng pivot wider

wider_01<-sale_revenue_channel_m %>%
  pivot_wider(
    names_from  = sales_channel,
    values_from = total_revenue,
    values_fill = 0,
    names_expand = TRUE
  ) 

C2: Dùng if_else

wider_02<-dta_sale%>%
  filter(delivery_date >= "2018-07-01", delivery_date <= "2020-12-31") %>%
  mutate(month = format.Date(delivery_date,"%Y-%m")) %>%
  group_by(month) %>%
  summarise(Distributor=round(sum(if_else(sales_channel == "Distributor", total_revenue, 0), 
                                  na.rm = TRUE) / 1E3, digits = 2),
            `In Store` = round(sum(if_else(sales_channel == "In-Store", total_revenue, 0), 
                                   na.rm = TRUE) / 1E3, digits = 2),
            Online = round(sum(if_else(sales_channel == "Online", total_revenue, 0), 
                               na.rm = TRUE) / 1E3, digits = 2),
            Wholesale = round(sum(if_else(sales_channel == "Wholesale", total_revenue, 0), 
                                  na.rm = TRUE) / 1E3, digits = 2))

Kết quả:

Note:

  • names_from: Cột chứa tên biến để chuyển thành các cột mới. Có thể tạo tên cột từ nhiều biến names_sep = “.”, names_prefix = “prod.”.

VD:

production %>% 
  pivot_wider(
    names_from = c(product, country), 
    values_from = production,
    names_glue = "prod_{product}_{country}"
  )
## # A tibble: 15 × 4
##     year prod_A_AI prod_B_AI prod_B_EI
##    <int>     <dbl>     <dbl>     <dbl>
##  1  2000    0.621    -0.464    -0.665 
##  2  2001    0.184     0.0719   -0.949 
##  3  2002   -0.132     0.588     1.05  
##  4  2003    1.47     -1.52     -1.30  
##  5  2004    0.643    -0.800     0.618 
##  6  2005    0.682     0.470    -0.261 
##  7  2006    0.520     0.627     0.269 
##  8  2007   -0.0482   -1.74     -2.61  
##  9  2008   -0.388    -0.824     0.0427
## 10  2009    0.240     0.654    -0.0945
## 11  2010   -0.0473    0.746    -0.908 
## 12  2011   -0.882    -0.734    -0.0252
## 13  2012   -0.555    -1.81     -0.812 
## 14  2013    0.641     0.502     1.33  
## 15  2014    0.778     1.12     -2.26
  • values_from: Cột chứa giá trị để đặt vào các cột mới tạo ra.

  • value_fill: Xác định giá trị sẽ điền vào những ô không có giá trị trong dữ liệu gốc. (NA sẽ thành 0)

  • id_expand giống names_expand: mở rộng (và sắp xếp) các hàng bị thiếu tiềm ẩn trong id_cols, cols.

Phần II

Đây là lương mỗi ngày của công nhân trong tháng:

Dùng pivot longer

longer_01<-casa %>%
  pivot_longer(
    #cols = !id,
    cols = starts_with("N"), 
    names_prefix = "N",
    names_transform = as.integer,
    names_to = "date", 
    values_to = "salary",
    values_drop_na = TRUE) 

Kết quả: