LunaticSoul
LunaticSoul

Reputation: 629

R - transform columns containing key values into multiple columns, in a data.frame object

Considering the following data.frame object df:

df <- data.frame(
  month = c(   1,    1,    1,    2,    2,    3,    3),
  type  = c("T1", "T1", "T4", "T2", "T3", "T1", "T3"),
  value = c(  10,   40,   20,   30,   10,   40,   50)
)

#   month type value
# 1     1   T1    10
# 2     1   T1    40
# 3     1   T4    20
# 4     2   T2    30
# 5     2   T3    10
# 6     3   T1    40
# 7     3   T3    50

How can df be processed to produce the result below?

#   month T1 T2 T3 T4
# 1     1 10  0  0  0
# 2     1 40  0  0  0
# 3     1  0  0  0 20
# 4     2  0 30  0  0
# 5     2  0  0 10  0
# 6     3 40  0  0  0
# 7     3  0  0 50  0

Upvotes: 0

Views: 39

Answers (1)

www
www

Reputation: 39174

library(tidyverse)

df2 <- df %>%
  mutate(ID = 1:n()) %>%
  spread(type, value, fill = 0) %>%
  select(-ID)

Upvotes: 1

Related Questions