I have sample data below and would like to use for loop
instead of ifelse
. Many thanks in advance.
df <- data.frame(Time = 0:24)
df$TimeBlock <- ifelse( 0 < df$Time & df$Time <= 6, "Night",
ifelse( 6 < df$Time & df$Time <= 12, "Morning",
ifelse( 12 < df$Time & df$Time <= 18, "Afternoon", "Evening")))
CodePudding user response:
Here is one way to use a for loop:
df$ltb = ""
for (i in seq_len(nrow(df))) {
if (0 < df$Time[i] && df$Time[i] <= 6) df$ltb[i] = "Night"
else if (6 < df$Time[i] && df$Time[i] <= 12) df$ltb[i] = "Morning"
else if (12 < df$Time[i] && df$Time[i] <= 18) df$ltb[i] = "Afternoon"
else df$ltb[i] = "Evening"
}
But a more R'ish would be:
df$ltb =
cut(
df$Time,
c(-Inf, 0, 6, 12, 18, 24),
labels = c("Evening", "Night", "Morning", "Afternoon", "Evening")
)
CodePudding user response:
cal_time <- function(dtime){
if (0 < dtime && dtime <= 6) output = "Night"
else if (6 < dtime && dtime <= 12) output = "Morning"
else if (12 < dtime && dtime <= 18) output = "Afternoon"
else output = "Evening"
output
}
df$TimeBlock = NA
for(i in 1:nrow(df)){
df[i,]$TimeBlock <- cal_time(dtime = df$Time[I])
}
A better alternative way:
cal_time <- function(dtime){
if (0 < dtime && dtime <= 6) output = "Night"
else if (6 < dtime && dtime <= 12) output = "Morning"
else if (12 < dtime && dtime <= 18) output = "Afternoon"
else output = "Evening"
output
}
df <- data.frame(Time = 0:24)
df$TimeBlock = apply(df, 1, cal_time)