Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how create new dataframe with number of occurrences of each strings on other dataframe, like a product list and products in basket sold

Tags:

r

Dataframe with each basket sold:

sells <- data.frame(buyers = c('buyer001', 'buyer002', 'buyer002'),
                      cart = c('apple > orange > grape > grape', 
                               'orange > orange', 'apple > grape'))

Dataframe with store stock

fruits <- data.frame(fruits = c('apple', 'orange', 'grape'))

Dataframe result

result <- data.frame(buyers = c('apple', 'orange', 'grape'),
                      cart = c(2, 3, 3))
like image 471
bfranc Avatar asked Nov 19 '25 19:11

bfranc


2 Answers

stack(table(unlist(strsplit(sells$cart, "\\W+"))))
  values    ind
1      2  apple
2      3  grape
3      3 orange
like image 65
KU99 Avatar answered Nov 21 '25 10:11

KU99


We can use the tidyverse (please see that the "fruits" object is not used)

library(dplyr)
library(tidyr)

sells %>%
    separate_rows(cart, sep = "\\s*>\\s*") %>%
    group_by(cart) %>%
    summarise(values = n())

# A tibble: 3 × 2
  cart   values
  <chr>   <int>
1 apple       2
2 grape       3
3 orange      3
like image 29
GuedesBF Avatar answered Nov 21 '25 10:11

GuedesBF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!