Skip to content
Prev 43475 / 398506 Next

in which column is an entry?

On Sat, 31 Jan 2004, Christian Schulz wrote:

            
Unfortunately Chuck's solution is a loop over rows, disguised by the use 
of apply.

Let us assume that the dataframe has all numeric entries and coerce to a 
matrix (as apply will, BTW).

tmp <- as.matrix(df)
tmp[is.na(tmp)] <- -1   # get rid of the NAs
tmp <- tmp >= 0         # a logical matrix
tmp <- cbind(tmp, TRUE) # add a fence column

I am happy to loop over 43 columns, though, so

for(i in 2:44) tmp[, i] <- tmp[, i] | tmp[, i-1]
for(i in 44:2) tmp[, i] <- tmp[, i] & !tmp[, i-1]
rtmp <- t(tmp)
z <- row(rtmp)[rtmp]
z[z==44] <- NA
z

is what you want.  It's a lot faster (about 12x).