I have the following data:
day = rep(c(24,25,26), 2)
status = c(1,1,1,0,0,0)
time = c(22313, 22106, 30192, 2340, 2219, 2401)
df = cbind.data.frame(day, status, time)
I want to reshape the data so that it goes from 6 rows to 3 (the days are no longer repeated) and I get a column for each type of status, and the time variable is converted to status1 and status0. Below is the final output I am looking for:
day = c(24,25,26)
time_status1 = c(22313, 22106, 30192)
time_status0 = c(2340, 2219, 2401)
df_new = cbind.data.frame(day, time_status0, time_status1)
df_new
CodePudding user response:
You can do this with pivot_wider
from the tidyr
package:
df |>
dplyr::arrange(status) |> # Not necessary if order of columns not important
tidyr::pivot_wider(
names_from = status,
values_from = time,
names_prefix = "time_status"
)
# # A tibble: 3 x 3
# day time_status0 time_status1
# <dbl> <dbl> <dbl>
# 1 24 2340 22313
# 2 25 2219 22106
# 3 26 2401 30192