[R] Vectorizing a loop
Petr Savicky
savicky at cs.cas.cz
Tue Feb 7 18:57:28 CET 2012
On Tue, Feb 07, 2012 at 11:39:42AM -0500, Alexander Shenkin wrote:
> 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
> }
>
> }
Hi.
Try the following.
cond1 <- (df[,3] %in% c(FALSE,NA)) & (df[,1] > 2 | df[,5])
df[,4] <- ifelse(cond1, 1, df[,4])
cond2 <- (df[,5] %in% c(TRUE, NA)) & (df[,2] == "b")
df[,4] <- ifelse(cond2, 2, df[,4])
df[,5] <- ifelse(cond2, TRUE, df[,5])
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list