假设我具有以下数据框:
df <- data.frame(Order=c("1234567","1234567","1234567","456789","456789"),Stage=c("Pipeline","Proposal","Closed","Pipeline","Lost"),StageChange=c("2008-01-01","2008-01-02","2008-01-03","2008-01-10","2008-01-12"))
结果:
head(df)
Order Stage StageChange
1 1234567 Pipeline 2008-01-01
2 1234567 Proposal 2008-01-02
3 1234567 Closed 2008-01-03
4 456789 Pipeline 2008-01-10
5 456789 Lost 2008-01-12
我需要拆开“阶段”(Stage)列并进入这样的数据框:
Order Pipeline Proposal Closed Lost
1 1234567 2008-01-01 2008-01-02 2008-01-03 NA
2 456789 2008-01-10 NA NA 2008-01-12
我阅读了文档,并尝试了dplyr和tidyr(like in this thread)的不同方法,但是我的无知正在赢得胜利。
有什么想法可以满足我的需求?
为了明确起见,我的目标是使用此数据来计算特定订单在特定阶段花费的天数。有些订单丢失,另一些则关闭(赢),这就是为什么存在“ NA”值的原因。当订单未更改到特定阶段时,也会发生同样的情况(订单可以从“流水线”转移到“丢失”,而无需对中间阶段进行任何更改)。
谢谢!
答案 0 :(得分:2)
您可以使用tidyr::pivot_wider
。这是退休功能spread
# install.packages("tidyr")
library(tidyr)
df %>%
pivot_wider(names_from = Stage, values_from = StageChange)
# # A tibble: 2 x 5
# Order Pipeline Proposal Closed Lost
# <fct> <fct> <fct> <fct> <fct>
# 1 1234567 2008-01-01 2008-01-02 2008-01-03 NA
# 2 456789 2008-01-10 NA NA 2008-01-12
答案 1 :(得分:1)
日期将是factor
类
library(tidyverse)
df_wide <- df %>%
tidyr::pivot_wider(names_from = Stage, values_from = StageChange)
df_wide
# A tibble: 2 x 5
Order Pipeline Proposal Closed Lost
<fct> <fct> <fct> <fct> <fct>
1 1234567 2008-01-01 2008-01-02 2008-01-03 NA
2 456789 2008-01-10 NA NA 2008-01-12
如果您想将日期转换为Date
类
df_wide_dates <- df %>%
tidyr::pivot_wider(names_from = Stage, values_from = StageChange) %>%
dplyr::mutate_at(., vars(Pipeline, Proposal, Closed, Lost), as.Date)
df_wide_dates
# A tibble: 2 x 5
Order Pipeline Proposal Closed Lost
<fct> <date> <date> <date> <date>
1 1234567 2008-01-01 2008-01-02 2008-01-03 NA
2 456789 2008-01-10 NA NA 2008-01-12
答案 2 :(得分:0)
使用random
dplyr::spread