【问题标题】:How to count different stages in R from one stage to another stage如何计算R中从一个阶段到另一个阶段的不同阶段
【发布时间】:2020-05-18 15:52:45
【问题描述】:

我是 R 新手,希望获得所需的输出

我的df是这样的,想把stage 3到stage 4,stage 3到stage 5,stage 3到stage 6, 我只对从 S3 到不同的第 4、5、6 阶段感兴趣,如果开始阶段是 S1 或其他什么,我也不需要,如果它是从 S3 到 S3 的特定一周,我们不需要

想要得到想要的结果

【问题讨论】:

  • 请使用dput(head(your_input_dataframe))分享输入数据
  • 发帖时请按照r标签页顶部的说明进行操作。特别是,提供可重现的输入——而不是图像。
  • @G.Grothendieck 我会从下一次开始,对不起,我是新手

标签: r dplyr


【解决方案1】:

这是一个整洁的选项:

library(dplyr)
library(tidyr)
set.seed(42)
dat <- tibble(
  week = as.Date("2018-01-01") + cumsum(sample(c(0L, 7L), size = 10, replace = TRUE)),
  begins = c(rep("S3", 9), "S1"),
  ends = sample(c("S4", "S5", "S6"), size = 10, replace = TRUE),
  stringsAsFactors = FALSE
)
dat
# # A tibble: 10 x 4
#    week       begins ends  stringsAsFactors
#    <date>     <chr>  <chr> <lgl>           
#  1 2018-01-08 S3     S5    FALSE           
#  2 2018-01-15 S3     S6    FALSE           
#  3 2018-01-15 S3     S6    FALSE           
#  4 2018-01-22 S3     S4    FALSE           
#  5 2018-01-29 S3     S5    FALSE           
#  6 2018-02-05 S3     S6    FALSE           
#  7 2018-02-12 S3     S6    FALSE           
#  8 2018-02-12 S3     S4    FALSE           
#  9 2018-02-19 S3     S5    FALSE           
# 10 2018-02-26 S1     S5    FALSE           

dat %>%
  filter(begins == "S3") %>%
  group_by(week, ends) %>%
  tally() %>%
  group_by(week) %>%
  pivot_wider(names_from = "ends", values_from = "n", values_fill = list(n = 0))
# # A tibble: 7 x 4
# # Groups:   week [7]
#   week          S5    S6    S4
#   <date>     <int> <int> <int>
# 1 2018-01-08     1     0     0
# 2 2018-01-15     0     2     0
# 3 2018-01-22     0     0     1
# 4 2018-01-29     1     0     0
# 5 2018-02-05     0     1     0
# 6 2018-02-12     0     1     1
# 7 2018-02-19     1     0     0

【讨论】:

  • 感谢枢轴是更好的解决方案,我正在过滤许多条件并获得答案,这更简洁
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 2020-05-29
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多