Pratham Pratham - 8 months ago 49
R Question

[R]Can this for loop with multiple ifs be vectorized?

[noob alert]I just learned a bit about vectorizing and its effect in code run times in R, so it came to my mind to try to vectorize my old codes if possible.
I have a for loop using multiple IFs, as a result quite slow. Can this be vectorized?

for(i in 1:nrow(merge24)){
if($Paid.Avg.x[i]) &$Paid.Avg.y[i])){
merge24$Tot.Paid.Avg[i] = NA
else if($Paid.Avg.x[i])){
merge24$Tot.Paid.Avg[i] = merge24$Paid.Avg.y[i]
else if($Paid.Avg.y[i])) {
merge24$Tot.Paid.Avg[i] = merge24$Paid.Avg.x[i]
else {
merge24$Tot.Paid.Avg[i] = (merge24$Paid.Avg.y[i] +merge24$Paid.Avg.x[i])/2


As pierre said with data.table (faster)

merge24 <- data.table(merge24)
merge24[, .(Paid.Avg.Tot = rowMeans(.SD, na.rm=TRUE)), .SDcols = c("Paid.Avg.x", "Paid.Avg.y")]