Suppose I have this dataframe, df:
UserID <- c(1, 1, 1, 5, 5)
PathID <- c(1,2,3,1,2)
Page <- c("home", "about", "services", "home", "pricing")
df <- data.frame(UserID, PathID, Page)
UserID PathID Page
1 1 1 home
2 1 2 about
3 1 3 services
4 5 1 home
5 5 2 pricing
I would like to know the next Page if Page = home. Not sure how to proceed. Any direction is much appreciated.
CodePudding user response:
With which
and 1, you can extract the value after page == "Home"
.
df$Page[which(df$Page == "home") 1]
[1] "about" "pricing"
You can also use dplyr::lead
:
dplyr::lead(df$Page)[df$Page == "home"]
[1] "about" "pricing"
CodePudding user response:
Another possible solution:
library(dplyr)
df %>%
mutate(pnext = if_else(Page == "home", lead(Page), NA_character_))
#> UserID PathID Page pnext
#> 1 1 1 home about
#> 2 1 2 about <NA>
#> 3 1 3 services <NA>
#> 4 5 1 home pricing
#> 5 5 2 pricing <NA>
In case we only need the result as a vector:
library(dplyr)
df %>%
mutate(pnext = if_else(Page == "home", lead(Page), NA_character_)) %>%
filter(!is.na(pnext)) %>%
pull
#> [1] "about" "pricing"
CodePudding user response:
In base it could be don with:
df$Page[c(FALSE, (df$Page == "home")[-nrow(df)])]
#[1] "about" "pricing"