rreshapelong-integerdcast

reshaping data using reshape() to wide format instead of dcast or pivot functions


I am having some problems understanding reshape function and would like to specifically use it as it uses base r.

Consider the following code

month <- c("jan", "feb", "mar", "apr")
hours <- c(40, 40, 35, 37)
days <- c(31, 28, 31, 30)

dat <- data.frame(month, hours, days)

In the above example, month, hours and days are the columns but I would like to transform this so that "hours" and "days" are rows within a column and 4 months in the "month" column are their own columns instead of rows/observations.

Any help would be appreciated. I've tried looking through other examples but can't seem to get my head around it.


Solution

  • I think what you're doing is rotating, aka transposing, the data frame, rather than reshaping it, and you can get what you want with just t(dat) or, to be fancier,

    dat.t <- as.data.frame(t(dat)[2:3,])
    names(dat.t) <- t(dat)[1,]
    print(dat.t)
    

    Which gives you:

          jan feb mar apr
    hours  40  40  35  37
    days   31  28  31  30