What will be the most efficient solution to order a data table based on a parent -> child relationship?
Given this nibble:
df <- tribble(
~user, ~page, ~from,
"user1", "home", "-",
"user1", "product page", "home",
"user1", "checkout", "promotion",
"user1", "promotion", "product page",
"user2", "home", "-",
"user2", "promotion", "home",
"user2", "checkout", "promotion" )
I want to produce this output:
df_results <- tribble(
~user, ~page, ~from, ~order,
"user1", "home", "-", 1,
"user1", "product page", "home", 2,
"user1", "promotion", "product page", 3,
"user1", "checkout", "promotion", 4,
"user2", "home", "-", 1,
"user2", "promotion", "home", 2,
"user2", "checkout", "promotion", 3 )
It's quite simple to identify the root element using something like:
df_results <- df %>%
mutate(order = if_else( from=="-",
1,
0)) %>%
group_by(user)
But I can't figure out any solution that not involve a “for” loop to go further with the sorting. The row in tibble for each users can be longer as the navigation step user performed on a website and pages has not a predefined order.