"Less" value is removed in R

Asked

Viewed 46 times

1

I have a df that contains negative times, for example:

-1:-14:-56

I would like to take all times that were less than 00:00:00 and put 00:00:00 in place.

I am currently doing a very manual job in replacing these objects:

df041[,1:61][df041[,1:61]=="-1:-38:-1"] <- "00:00:00"
df041[,1:61][df041[,1:61]=="-1:00:-33"] <- "00:00:00"
df041[,1:61][df041[,1:61]=="-8:-57:-54"] <- "00:00:00"

Does anyone have any idea how to do that?

1 answer

5


Here’s a solution with the package lubridate.
Start by defining a function, negativo, which only modifies the values with the format "HH:MM:SS" where at least one of these numbers is negative. Then apply this function to the dataframe columns.

library(lubridate)

negativo <- function(x, replace = "00:00:00"){
  y <- hms(x)
  h <- hour(y) < 0
  m <- minute(y) < 0
  s <- second(y) < 0
  x[h | m | s] <- replace
  x
}

negativo(c("-1:-38:-1", "-1:00:-33", "-8:-57:-54"))
#[1] "00:00:00" "00:00:00" "00:00:00"


df041[, 1:61] <- lapply(df041[, 1:61], negativo)

The function is tested, the sapply it is not since there is no test data but I do not believe there are problems.

  • Perfect! Thank you so much. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.