Using ave and suppose your dat data
dat$Fx <- with(dat,ave(Y,list(X),FUN=length)) dat$Fyx <- with(dat,ave(Y,list(X,Y),FUN=length))
Result:
XYZ Fx Fyx 1 A 1 0 2 1 2 A 2 1 2 1 3 B 1 1 3 2 4 B 2 1 3 1 5 B 1 0 3 2
If the data does not have a numeric column for ave to work, then:
dat$Fx <- with(dat,ave(seq_len(nrow(dat)),list(X),FUN=length)) dat$Fyx <- with(dat,ave(seq_len(nrow(dat)),list(X,Y),FUN=length))
source share