Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. # tidyr::hoist()
  2. x %>%
  3. filter(activityType == 'ECOMMERCE') %>%
  4. select(id, sessionId, activityTime, activityType, ecommerce, customDimension) %>%
  5. hoist(ecommerce,
  6. action_type = c('actionType'),
  7. transaction_id = c('transaction', 'transactionId'),
  8. transaction_revenue = c('transaction', 'transactionRevenue'),
  9. products = 'products',
  10. ecommerce_type = 'ecommerceType') %>%
  11. unnest_longer(products) %>% unnest_wider(products) %>%
  12. filter(!is.na(transaction_id)) %>%
  13. select(-ecommerce, -customDimension)
  14.  
  15. # map inside mutate
  16. x %>%
  17. filter(activityType == "ECOMMERCE") %>%
  18. select(id, sessionId, activityTime, ecommerce) %>%
  19. mutate(transaction = map(ecommerce, "transaction"),
  20. transactionRevenue = map_dbl(transaction, ~.[["transactionRevenue"]] %||% NA),
  21. transactionId = map_chr(transaction, ~.[["transactionId"]] %||% NA)) %>%
  22. filter(!is.na(transactionRevenue)) %>%
  23. mutate(actionType = map_chr(ecommerce, ~.[['actionType']] %||% NA),
  24. products = map(ecommerce, 'products')) %>%
  25. unnest(products) %>%
  26. mutate(productSku = map_chr(products, ~.[['productSku']]),
  27. productName = map_chr(products, ~.[['productName']]),
  28. itemRevenue = map_chr(products, ~.[['itemRevenue']]) %>% as.numeric(),
  29. productQuantity = map_chr(products, ~.[['productQuantity']]) %>% as.numeric()) %>%
  30. select(-transaction, -ecommerce, -products)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement