mercredi 8 avril 2015

R row-wise calculation in nested ifelse() - How to improve performance?

In this forum I found a nice way to do row-wise calculation of values in R, which are then stored in a newly created column (c3).


In the code provided below the nested ifelse() statement examplifies an example with three levels (a1 ranges from 1 to 3).



a1 <- 1 # variable 1; for this example it's either 1 or not.
a2 <- 2 # range: up to 10 values (e.g. for this example 1:10)

c1 <- c(1:6) # column 1 as sample data set
c2 <- c(11:16) # column 2 as sample data set

# column 3 calculated based on row wise operations
c3 <- ifelse(a1==1 & a2==1,1,ifelse(a1==1 & a2==2,2,ifelse(a1==1 & a2==3,3,4)))

r <- t(rbind(c1,c2,c3))
r


Now I need the ifelse() statement nested 10 (!) times (at least). Something like


ifelse(a1 == 1 & a2 ==1,,ifelse(a1 == 1 & a2 ==2,,ifelse(a1 == 1 & a2 ==3,,ifelse(a1 == 1 & a2 ==4,,ifelse(a1 == 1 & a2 ==5,,ifelse(a1 == 1 & a2 ==6,,ifelse(a1 == 1 & a2 ==7,,ifelse(a1 == 1 & a2 ==8,,ifelse(a1 == 1 & a2 ==9,,))))))))).


While such a nested ifelse() statement might be fine for 2 or 3 levels, I wonder whether more experienced R programmers know of a more efficient (faster performing) way to do these 10 nested row-wise manipulations.


May I add: depending on the level of nesting different calculations have to be done. Thus for example (1) looks in real life more like (2).



(1) ifelse(a1==1 & a2==1,1, etc)
(2) ifelse(a1==1 & a2==1,variable1*(1+variable2 /variable3), etc)


Thanks for any help and advice to improve R coding!


System: Mac OS X Mavericks, RStudio: R version 3.1.1 (2014-07-10)


Aucun commentaire:

Enregistrer un commentaire