2017-04-06 44 views
8

我的數據是這樣的:

enter image description here流傳着重複的標識(使用tidyverse和%>%)

我想使它看起來像這樣:

enter image description here

我希望使用%>% - 鏈接進行反轉。

df <- 
structure(list(id = c(2L, 2L, 4L, 5L, 5L, 5L, 5L), start_end = structure(c(2L, 
1L, 2L, 2L, 1L, 2L, 1L), .Label = c("end", "start"), class = "factor"), 
    date = structure(c(6L, 7L, 3L, 8L, 9L, 10L, 11L), .Label = c("1979-01-03", 
    "1979-06-21", "1979-07-18", "1989-09-12", "1991-01-04", "1994-05-01", 
    "1996-11-04", "2005-02-01", "2009-09-17", "2010-10-01", "2012-10-06" 
    ), class = "factor")), .Names = c("id", "start_end", "date" 
), row.names = c(3L, 4L, 7L, 8L, 9L, 10L, 11L), class = "data.frame") 

我曾嘗試:

data.table::dcast(df, formula = id ~ start_end, value.var = "date", drop = FALSE) # does not work because it summarises the data 

tidyr::spread(df, start_end, date) # does not work because of duplicate values 


df$id2 <- 1:nrow(df) 
tidyr::spread(df, start_end, date) # does not work because the dataset now has too many rows. 

這些問題不回答我的問題:

Using spread with duplicate identifiers for rows(因爲他們總結)

R: spread function on data frame with duplicates(因爲它們的值粘貼在一起)

Reshaping data in R with "login" "logout" times(因爲沒有專門詢問/使用反轉和鏈接回答)

+0

'as.data.table(DF)spread [,.ID: =序列(.N),。(id,start_end)] [,dcast(.SD,.id + id〜start_end,value.var =「date」)]'? – A5C1D2H2I1M1N2O1R2T1

+0

使用'reshape2'和'dplyr':'df%>%group_by(id,start_end)%>%arrange(date)%>%mutate(sequence = 1:n())%>%dcast(id + sequence〜 start_end,value =「date」)'。 – eipi10

回答

10

我們可以使用tidyverse。由 'start_end', 'ID' 分組後,創建序列列 'IND',然後從 '長' 到 '寬' 格式

library(dplyr) 
library(tidyr) 
df %>% 
    group_by(start_end, id) %>% 
    mutate(ind = row_number()) %>% 
    spread(start_end, date) %>% 
    select(start, end) 
#  id  start  end 
#* <int>  <fctr>  <fctr> 
#1  2 1994-05-01 1996-11-04 
#2  4 1979-07-18   NA 
#3  5 2005-02-01 2009-09-17 
#4  5 2010-10-01 2012-10-06