jlaufenb
jlaufenb

Reputation: 66

Column index of last occurrence of value in each row

I need to determine the column index for the first and final occurrence of a specific value in each row of a matrix. For example, if my matrix is the following:

 0  10  10  10   0   0
10  10  10   0   0   0
 0   0   0   0  10  10

and I need a vector containing the column indices of the first occurrence of 10 in each row and a vector of the final occurrence, the resulting vectors would be (2,1,5) and (4,3,6), respectively.

I wrote the following function used it with the apply function to find the first occurrence:

Myfunc   <- function(x){which==10)[1]
Myfirst  <- apply(x,1,Myfunc)

However, I can't seem to figure out how to get a vector for the final occurrence. Can someone show me how to use the which() function to do this or suggest an alternative method?

Upvotes: 3

Views: 1755

Answers (2)

harkmug
harkmug

Reputation: 2785

v1 = apply(df,1,function(x){head(which(x==10),1)}) #First 
v2 = apply(df,1,function(x){tail(which(x==10),1)}) #Last

A worked out example:

df = rbind(c(0,10,10,10,0,0),c(10,10,10,0,0,0),c(0,0,0,0,10,10))

> df
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0   10   10   10    0    0
[2,]   10   10   10    0    0    0
[3,]    0    0    0    0   10   10

v1 = apply(df,1,function(x){head(which(x==10),1)}) #First 
> v1
[1] 2 1 5
> is.vector(v1)
[1] TRUE

v2 = apply(df,1,function(x){tail(which(x==10),1)})
> v2
[1] 4 3 6
> is.vector(v2)
[1] TRUE

Upvotes: 4

gung - Reinstate Monica
gung - Reinstate Monica

Reputation: 11893

@rmk's answer will work (+1). You might also be interested in the doBy package. It contains a firstobs() and a lastobs() function that will do what you want. You could, for example, substitute them in for @rmk's handwritten functions.

Upvotes: 0

Related Questions