0

I have a data frame with multiple observations in a single day over different times on that day. Currently, each time point has a separate row. I would like to reformat the data frame so that each day has one row and each time point on that day is in a different column. The data frame looks like the following:

set.seed(1)
df <- data.frame( time = rep(seq(1:5),each=5),
                  day      = c(  "10-02" ,  "10-03"  ,  "10-04" ,   "10-05" ,  "10-06" )
                  ,temp = sample(1:25,replace = TRUE)
                  )

How can I reformat it so that data looks instead like this?

data.frame(day = c("10-02","10-03")
           ,time1 = c(25,4)
           ,time2 = c(23,11)
           ,time3 = c(1,21)
           ,time4 = c(14,21)
           ,time5 = c(21,10))

Thank you for your help!

I Wright
  • 51
  • 5
  • You may do `library(tidyr);library(dplyr);df %>% mutate(time = paste0('time', time)) %>% pivot_wider(names_from = time, values_from = temp)` – akrun Feb 04 '22 at 19:04

0 Answers0