I have a string variable tours in my dataframe df that represents the different stops an individuum did during a journey.
For example:
1. home_work_leisure_home
2. home_work_shopping_work_home
3. home_work_leisure_errand_home
In Transport planning we group activities in primary (work and education) and secondary activities (everything else). I want to count the number of secondary activities before the first primary activity, inbetween two primary activities after the last primary activity for each tour.
This means I am looking for a function in R that:
a. identifies the first work in the string variable,
b. then counts the number of activities before this first work activity
c. then identifies the last work in the string if there is more than one
d. if there is then count the number of activities between the two work activities,
e. then count the number of activities after the last work activity
The result for the three example tours then would be:
- number of activities before first primary: 1 (home)
number of activities between first and last primary: 0
number of activities after last primary: 2 (leisure & home)
number of primary activities: 1 (work) - number of activities before first primary: 1 (home)
number of activities between first and last primary: 1 (shopping)
number of activities after last primary: 1 (home)
number of primary activities: 2 (work) - number of activities before first primary: 1 (home)
number of activities between first and last primary: 0
number of activities after last primary: 3 (leisure, errand & home)
number of primary activities: 1 (work)
I would be super thankful if someone could give me a hand with this issue - even if it is a link to a similar question.
Tank you. Kind regards Nathalie