Skip to content
Prev 301069 / 398503 Next

First value in a row

If there are a lot more rows than columns in your data.frame then looping
over columns is faster than looping over rows.   Comparing 
f2 <- function (dataFrame) 
{
    retval <- dataFrame[, 1]
    for (col in dataFrame[-1]) {
        na <- is.na(retval)
        if (!any(na)) 
            break
        retval[na] <- col[na]
    }
    retval
}
to the looping over row version
f1 <- function (dataFrame)  apply(dataFrame, 1, function(x) x[!is.na(x)][1])

for a 250,000 row by 3 coludata.frame, f1 takes 2.48 seconds and f1 0.02.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com