Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert long data to wide in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading