I have a four column matrix with a chronological index, and three columns of names (strings). Here is some toy data:

```
x = rbind(c(1,"sam","harry","joe"), c(2,"joe","sam","jack"),c(3,"jack","joe","jill"),c(4,"harry","jill","joe"))

```

I want to create three additional vectors that count (for each row) any previous (but not subsequent) occurrences of the name. Here would be the desired result for the toy data:

```
y = rbind(c(0,0,0),c(1,1,0),c(1,2,0),c(1,1,3))

```

I am at a loss of how to approach the problem, and have searched Stack Overflow for relevant examples. dplyr provides answers for finding total counts, but (as far as I can tell) not on a row by row basis. 

I attempted to write a function to deal with this problem in a single-column space, but with no luck, i.e.

```
thing = sapply(x,function(i)length(grep(i,x[x[1:i]])))

```

Any tips would be appreciated.