How to rearrange column into two new columns in R

I have a dataset as shown below. I'd like to know how to rearrange the dataset so that the hours are sorted into two new columns - One for 'Day' and one for 'Night.

Current data layout:

PERIOD| HOURS
day| 2.5
night| 3.2
day| 6.1
night| 1.2
day| 0.5
night| 2.3

I'd like to get:

DAY| NIGHT
2.5| 3.2
6.1| 1.2
0.5| 2.3

NB: There are in fact 336 observations for Hours. My data.frame is called DNH.

library(tidyverse)

data.frame(p=rep(c("d","n"),3),
           h=1:6) %>% 
  pivot_wider(names_from="p",
              values_from="h") %>% 
  unnest(cols = everything())

Thanks for the comment - I tried copying and pasting your code and replaced df with name of my file but it won't work. The data provided here is only a sample, there are in fact 336 observations for Hours if that matters.

DNH(p=rep(c("Day","Night"),3),
h=1:6) %>%
pivot_wider(names_from="Period",
values_from="Hours") %>%
unnest(cols = everything())

Error in DNH(p = rep(c("Day", "Night"), 3), h = 1:6) :
could not find function "DNH"

You need to replace the entire first two lines with your data frame instead of just the data.frame function.

DNH %>%
  pivot_wider(
    names_from="Period",
    values_from="Hours"
  ) %>% 
  unnest(cols =c(day, night))

Also note that if your column names are capitalized, you must make "Period" and "Hours" capitalized as well in your pivor_wider() call.

The first two lines in the code @nirgrahamuk provided are an example data set. Take a look at the tidyr vignette on transforming data (Pivoting • tidyr).

1 Like

Thank you! The code is now working for me.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.