Say I have a for loop that looks like this.
person <- c("Mike", "Kim", "Fred", "Steve", "Quail", "bean")
sleep <- c(5, 10, 3, 7, 1, 5)
dat <- data.frame(person, sleep)
for (i in 1:length(dat$person)) {
if (dat$sleep[i] >= 7) {
dat$fatigue[i] <- 0
}
if (dat$sleep[i] > 5 & dat$sleep[i] < 7) {
dat$fatigue[i] <- 1
}
if (dat$sleep[i] >= 3 & dat$sleep[i] <= 5) {
dat$fatigue[i] <- 2
}
if (dat$sleep[i] < 3) {
dat$fatigue[i] <- 3
}
}
How would I write this for loop with the if statements using the apply functionality of R?
I am rather new to using this and any help would be appreciated.
Please let me know if you have any questions.
Thank you.
We can try using case_when
from the dplyr
library
dat$fatigue <- case_when(
dat$sleep < 3 ~ 3,
dat$sleep >= 3 & dat$sleep <= 5 ~ 2,
dat$sleep > 5 & dat$sleep < 7 ~ 1,
dat$sleep >= 7 ~ 0,
TRUE ~ -1
)
Note that case_when()
, like many functions in R, is already vectorized. Therefore, you don't need to use an explicit for
loop.