0

I have a dataframe where one column shows hour type and another shows number of hours, but I want it to be a dataframe where each hour type has its own column.

Like from this:

name   hourtype   hours 

Amy       A         3
Amy       B         2   
Bob       B         1   
Bob       C         4
Cam       A         5
Cam       B         1
Cam       C         1
Dan       A         2 

To this:

name   A   B   C

Amy    3   2   0
Bob    0   1   4   
Cam    5   1   1
Dan    2   0   0

1 Answers1

0

Try this. Your issue is mainly to the format of data. You have data in long format so you want now in wide format. The function pivot_wider() from tidyr, a tidyverse package can help with that. After this, you can set NA values to zero with replace. Here the code:

library(tidyverse)
#Code
df %>% pivot_wider(names_from = hourtype,values_from=hours) %>%
  replace(is.na(.),0)

The output:

# A tibble: 4 x 4
  name      A     B     C
  <chr> <int> <int> <int>
1 Amy       3     2     0
2 Bob       0     1     4
3 Cam       5     1     1
4 Dan       2     0     0

Some data used:

#Data
df <- structure(list(name = c("Amy", "Amy", "Bob", "Bob", "Cam", "Cam", 
"Cam", "Dan"), hourtype = c("A", "B", "B", "C", "A", "B", "C", 
"A"), hours = c(3L, 2L, 1L, 4L, 5L, 1L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))
Duck
  • 39,058
  • 13
  • 42
  • 84