【问题标题】:How to generate multiple rows conditioned on the current rows using dplyr in R?如何在 R 中使用 dplyr 生成以当前行为条件的多行?
【发布时间】:2021-05-28 12:24:47
【问题描述】:

我有一个包含多个 4 位代码的数据框。根据第三位数字的值,我想通过以下方式操作数据框:

  1. 如果第 3 位 != "0" 什么都不做
  2. 如果第 3 位 == “0”,则消除此元素并将其替换为以下一个 xx{10-99}。其中 xx 是元素的前两位初始数字,{10-99} 表示应将 {xx10,xx11,xx12,...,xx99} 添加到数据框中。

有什么想法可以用 dplyr 来实现吗? 提前致谢!

例如

df <- data.frame("id"= c("1111","1231","1000","2222","2900")
df

我想将 df 转换为以下 df

{"1111","1231","1010","1011",...,"1099","2222","2910","2911",..."2999"}

【问题讨论】:

  • 请附上您尝试过的代码。如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example
  • 感谢 DimitrisPassas 从一些示例数据开始。一些想法:(1)print(df) 没有它的输出是无关紧要的,即使这样我也不认为它增加了任何东西(因为df 确实是不言而喻的); (2) 你修复了它,但请不要在原始数据中添加高亮,这会破坏我们正在寻找的模式。也就是说,"10**00**" 击败了“第三个字符”比较,并要求我们手动编辑样本数据。该修复程序更有用。输出是暗示性的并且足够清晰,通常“预期输出”在正确的 R class 中,例如截断的帧。谢谢!

标签: r dataframe dplyr


【解决方案1】:
library(dplyr)
dat <- tibble(id = 1:2, code = c("1111", "2201"))
dat
# # A tibble: 2 x 2
#      id code 
#   <int> <chr>
# 1     1 1111 
# 2     2 2201 

dat %>%
  filter(substr(code, 3, 3) == "0") %>%
  rowwise() %>%
  do({
    newcodes <- sprintf("%02i", 0:3)
    mutate(as_tibble(.)[rep(1, length(newcodes)),],
           code = paste0(substr(code, 1, 2), newcodes))
  }) %>%
  bind_rows(filter(dat, substr(code, 3, 3) != "0"), .)
# # A tibble: 5 x 2
#      id code 
#   <int> <chr>
# 1     1 1111 
# 2     2 2200 
# 3     2 2201 
# 4     2 2202 
# 5     2 2203 

我是从00到03,你可以随便填。

【讨论】:

    【解决方案2】:

    使用tidyr::uncount的另一种方法

    df <- data.frame("id" = c("1111","1231","1000","2222","2900"))
    
    library(tidyverse)
    df %>% uncount(ifelse(substr(id, 3, 3) == '0', 90, 1)) %>%
      group_by(id) %>%
      mutate(id = ifelse(substr(id, 3, 3) == '0', 
                            paste0(substr(id, 1, 2), row_number() + 9), 
                            id)) %>%
      ungroup
    #> # A tibble: 183 x 1
    #>    id   
    #>    <chr>
    #>  1 1111 
    #>  2 1231 
    #>  3 1010 
    #>  4 1011 
    #>  5 1012 
    #>  6 1013 
    #>  7 1014 
    #>  8 1015 
    #>  9 1016 
    #> 10 1017 
    #> # ... with 173 more rows
    

    reprex package (v2.0.0) 于 2021-05-28 创建

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2023-03-03
      • 2019-03-09
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多