Reputation: 3
I have a massive column of dates with time. I want to change it to “BP” for before pandemic and “AP” for after pandemic depending on the date. Any date after 2020-04-20 would be AP and anything before is BP.
I tried using gsub
to change it and the ifelse
function but that did not work.
The format of the date is yyyy-mm-dd
hh-mm-ss
. The type is double.
Upvotes: 0
Views: 42
Reputation: 66775
my_data <- data.frame(
date = as.POSIXct(c(
"2020-04-01 12:34:56",
"2020-04-21 01:23:45"))
)
my_data
#> date
#> 1 2020-04-01 12:34:56
#> 2 2020-04-21 01:23:45
# create a new variable called pandemic
my_data$pandemic = ifelse(my_data$date >= as.POSIXct("2020-04-20 00:00:00"),
"AP",
"BP")
my_data
#> date pandemic
#> 1 2020-04-01 12:34:56 BP
#> 2 2020-04-21 01:23:45 AP
Or if you really want to overwrite the date
column and change to a character type, use:
my_data$date = ifelse(my_data$date >= as.POSIXct("2020-04-20 00:00:00"),
"AP", "BP")
my_data
#> date
#> 1 BP
#> 2 AP
Upvotes: 1