考虑以下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
答案 0 :(得分:1)
library(tidyverse)
df2 <- df %>%
mutate(ID = 1:n()) %>%
spread(type, value, fill = 0) %>%
select(-ID)