Ras*_*sen 10 r dplyr tidyr dcast tidyverse
我想使用%>% - chaining在tidyverse中执行此操作.
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")
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
这些问题没有回答我的问题:
使用包含行的重复标识符的扩展 (因为它们汇总)
R:在具有重复项的数据框上传播函数 (因为它们将值粘贴在一起)
用"登录""注销"次数重新整理R中的数据(因为没有特别要求/回答使用tidyverse和链接)
akr*_*run 17
我们可以用tidyverse.在按'start_end','id'分组后,创建一个序列列'ind',然后spread从'long'到'wide'格式
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5313 次 |
| 最近记录: |