Ask Your Question
4

How to convert for loops and if else statements into vectors in R?

asked 2022-01-17 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-15 11:00:00 +0000

woof gravatar image

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:

  1. For loop to vector:
# For loop approach
for (i in 1:5){
  print(i)
}

# Vectorized approach
1:5
  1. If else statement to vector:
# If else approach
x <- 5
if (x > 0) {
  y <- 1
} else {
  y <- -1
}

# Vectorized approach
y <- ifelse(x > 0, 1, -1)
  1. For loop with condition to vector:
# 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)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-17 11:00:00 +0000

Seen: 7 times

Last updated: May 15 '21