| Store_id | Product | Count |
| --------------------------------|
| 6 | Soda | 10 |
| 8 | Chips | 24 |
| 9 | Candy | 5 |
I basically have an above table. I want to make Store_id the rows and product the columns and have count as the values of the table. This is basically a user-interactions matrix/utility matrix.
How can i convert this DF to another DF of the aforementioned form?
output:
store_id soda chips candy
6 10 0 0
8 0 24 0
9 0 0 5
Maybe something like this
library(tidyverse)
df_example <- tibble::tribble(
~Store_id, ~Product, ~Count,
6, "Soda", 10,
8, "Chips", 24,
9, "Candy", 5
)
df_example %>%
pivot_wider(names_from = Product, values_from = Count,values_fill = 0)
#> # A tibble: 3 x 4
#> Store_id Soda Chips Candy
#> <dbl> <dbl> <dbl> <dbl>
#> 1 6 10 0 0
#> 2 8 0 24 0
#> 3 9 0 0 5
Created on 2020-06-10 by the reprex package (v0.3.0)
An option with base R
using xtabs
xtabs(Count ~ Store_id + Product, df_example)
# Product
#Store_id Candy Chips Soda
# 6 0 0 10
# 8 0 24 0
# 9 5 0 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.