1

how do I change row names within this variable in my data frame? I would like to change all ActivityHour 00AM 1AM 2AM 8AM 9AM 10AM 11AM 12PM 1PM 2PM 3PM

structure(list(Id = c("user_1", "user_1", "user_1", "user_1", 
"user_1", "user_1", "user_1", "user_1", "user_1", "user_1"), 
ActivityHour = c("0:00", "1:00", "2:00", "8:00", "9:00", 
"10:00", "11:00", "12:00", "13:00", "14:00"), TotalIntensity = c(20, 
8, 7, 13, 30, 29, 12, 11, 6, 36), AverageIntensity = c(0.333333, 
0.133333, 0.116667, 0.216667, 0.5, 0.483333, 0.2, 0.183333, 
0.1, 0.6)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

Thank you!

Stackstudent_09
  • 131
  • 1
  • 9

1 Answers1

2

You are changing the variable ActivityHour. You are not changing row names which for your example are c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"). This will change the ActivityHour variable assuming the data structure you provided is called example:

hours <- paste0(0:23, ":00")
ampm <- paste0(c(0:12, 1:11), c(rep("AM", 12), rep("PM", 12)))
timetable <- data.frame(hours, ampm)
example$ActivityHour
#  [1] "0:00"  "1:00"  "2:00"  "8:00"  "9:00"  "10:00" "11:00" "12:00" "13:00" "14:00"
example$ActivityHour <- timetable$ampm[match(example$ActivityHour, timetable$hours)]
example$ActivityHour
#  [1] "0AM"  "1AM"  "2AM"  "8AM"  "9AM"  "10AM" "11AM" "12PM" "1PM"  "2PM" 
dcarlson
  • 10,936
  • 2
  • 15
  • 18
  • Clever! I couldn't figure out how to get "0AM". Nice one – jared_mamrot Apr 05 '22 at 23:57
  • Wow! Okay cool I think I got it. so you are creating 0:00 through 23:00 hours and then 00:00 am to 12:00 AM (which by the way should be 00:00 through 00:11 because 00:12 should be PM) and then 1:00PM to 11:00PM. then matching the original activity hour category to the new hour category and assigning the ampm variable to it, essentially? – Stackstudent_09 Apr 07 '22 at 23:35
  • 1
    Yes. Just change `c(rep("AM", 13), rep("PM", 11)` to `c(rep("AM", 12), rep("PM", 12)`. I've made that change above. – dcarlson Apr 07 '22 at 23:38