R - 在data.frame对象中将包含键值的列转换为多个列

时间:2017-05-05 02:42:44

标签: r

考虑以下data.frame对象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

如何处理df以生成以下结果?

#   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

1 个答案:

答案 0 :(得分:1)

library(tidyverse)

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