So I am working on a data frame on a column that should say hours of sleep per night however using difftime() function has given values which show the number of hours sleep in negative values for some and the number of hours awake in positive values for others. I want to subtract 24 from just those who are above 0 (non negative numbers) so I have done:
data$Sleep.time <- with(data = data, difftime(Bed.time, Waking.up.time, units = "hours"))
data$Sleep.time <- as.numeric(data$Sleep.time)
data$subtract <- (24)
data$Sleep.time <- if (data$Sleep.time>0) {data$Sleep.time - data$subtract}
So this just takes 24 away from all of the values so my values that are already negative are completely wrong. I'm not quite sure how to use the if function so this works properly any help would be great!
CodePudding user response:
if
is not vectorized i.e. it expects a logical expression with length 1
. The 'Sleep.time' column will have more than one element. We may either use ifelse
or create an index and use it to subtract and assign
i1 <- data$Sleep.time> 0
data$Sleep.time[i1] <- data$Sleep.time[i1] - data$subtract[i1]
CodePudding user response:
You could try using ifelse something like this
data$Sleep.time <- ifelse(data$Sleep.time > 0, data$Sleep.time - 24, data$Sleep.time)
Syntax: ifelse(condition, if true, else) returns a vector if the condition is applied on a vector. Hope it helps and this is vectorized, so much faster than a loop.