Take only the last N values from r$values
and r$lengths
:
foo <- function(x,N){
r <- rle(as.character(x))
lastN<-max(1,(length(r$lengths) - N + 1)):length(r$lengths)
short <- paste0(r$values[lastN], collapse="_")
long <- paste0(r$values[lastN], "(", r$lengths[lastN], ")", collapse="_")
data.frame(short, long)
}
ddply(paths, .(path), function(x) foo(x$touchpoint,N=2))
path short long
1 abc B_C B(1)_C(1)
2 def C_D C(1)_D(1)
3 ghi A_C A(3)_C(1)
4 jkl B_C B(1)_C(1)
5 mno A_C A(2)_C(1)
6 pqr A_C A(1)_C(1)
ddply(paths, .(path), function(x) foo(x$touchpoint,N=4))
path short long
1 abc A_B_C A(2)_B(1)_C(1)
2 def B_D_C_D B(1)_D(1)_C(1)_D(1)
3 ghi A_C A(3)_C(1)
4 jkl A_B_C A(2)_B(1)_C(1)
5 mno B_A_C B(1)_A(2)_C(1)
6 pqr A_C A(1)_C(1)
EDIT: Edited the function to take last N values, not the first.