-1

Hi I have a sample data frame like this

Time <- c('0:00', '1:00', '2:00', '13:00', '14:00')
Time = data.frame(x)

So what I would like to do is create another column "AMPM" based on the "Time" column. "AMPM" should able to show if the time is in AM or PM

The final output should look like this

   Time AMPM
1  0:00   AM
2  1:01   AM
3  2:09   AM
4 13:52   PM
5 14:06   PM
6 15:33   PM
7 16:27   PM
8 21:40   PM
dummy123
  • 31
  • 4
  • 5
    Is your data stored as a character? Or some time data type? It would be easier to help if you provided data in a [reproducible format](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) rather than as an image because it's not really possible to tell how data is stored in an image. – MrFlick Sep 08 '20 at 06:43
  • Hi, sorry for the inconvenience. I have edited my question. I hope this would help in trying to understand what I want to do – dummy123 Sep 08 '20 at 07:02

1 Answers1

2

You can remove everything after colon, convert data to integer and assign 'PM' to all the values greater than 11 and "AM" otherwise.

df <- data.frame(Time = c('0:00', '1:00', '2:00', '13:00', '14:00'))
df$AMPM <- ifelse(as.integer(sub(':.*', '', df$Time)) > 11, 'PM', 'AM')
#Without ifelse
#c('AM', 'PM')[(as.integer(sub(':.*', '', x)) > 11) + 1]
df
#   Time AMPM
#1  0:00   AM
#2  1:00   AM
#3  2:00   AM
#4 13:00   PM
#5 14:00   PM
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178