[R] Vectorizing a loop

Alexander Shenkin ashenkin at ufl.edu
Tue Feb 7 17:39:42 CET 2012


Hello Folks,

I'm trying to vectorize a loop that processes rows of a dataframe.  It
involves lots of conditionals, such as "If column 10 == 3, and if column
3 is True, and both column 5 and 6 are False, then set column 4 to True".

So, for example, any ideas about vectorizing the following?

df = data.frame( list(a=c(1,2,3,4), b=c("a","b","c","d"), c=c(T,F,T,F),
d=NA, e=c(F,F,T,T)) )

for (i in 1:nrow(df)) {

    if (df[i,3] %in% c(FALSE,NA) & (df[i,1] > 2 | df[i,5]) ) {
        df[i,4] = 1
    }

    if (df[i,5] %in% c(TRUE, NA) & df[i,2] == "b") {
        df[i,4] = 2
        df[i,5] = T
    }

}

Thanks,
Allie



More information about the R-help mailing list