Pratham - 6 months ago 41

R Question

[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(is.na(merge24$Paid.Avg.x[i]) & is.na(merge24$Paid.Avg.y[i])){

merge24$Tot.Paid.Avg[i] = NA

}

else if(is.na(merge24$Paid.Avg.x[i])){

merge24$Tot.Paid.Avg[i] = merge24$Paid.Avg.y[i]

}

else if(is.na(merge24$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

}

}

Answer

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")]
```