To convert for loops and if else statements into vectors in R, we usually use vectorized functions. Vectorized functions are designed to apply a function over a vector or a matrix, without the need for explicit for loops.
Here are some examples:
# For loop approach
for (i in 1:5){
print(i)
}
# Vectorized approach
1:5
# If else approach
x <- 5
if (x > 0) {
y <- 1
} else {
y <- -1
}
# Vectorized approach
y <- ifelse(x > 0, 1, -1)
# For loop approach
out <- numeric(5)
for (i in 1:5) {
if (i %% 2 == 0) {
out[i] <- i * 2
} else {
out[i] <- i
}
}
# Vectorized approach
out <- ifelse(1:5 %% 2 == 0, 1:5 * 2, 1:5)
Asked: 2022-01-17 11:00:00 +0000
Seen: 9 times
Last updated: May 15 '21