-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
  • 6
  • 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
  • 377,200
  • 20
  • 156
  • 213
  • Hi thanks for your reply. But my dataset has other time values as well such as 08:38, 12:40 etc. So it would take forever for me to use this method – dummy123 Sep 08 '20 at 06:54
  • 1
    @dummy123 please try the example, which works for 08:38, 12:40 and so on. – denis Sep 08 '20 at 06:57
  • @dummy123 You don't have to manually type in each value. Read the data in R `df <- read.csv('filename.csv')` and then use the above method assuming the column name is `Time`. – Ronak Shah Sep 08 '20 at 07:01
  • Fantastic. Thanks for your help! – dummy123 Sep 08 '20 at 07:11