【问题标题】:Replace ordered columns after first occurrence of value在第一次出现值后替换有序列
【发布时间】:2018-09-07 02:08:40
【问题描述】:

每当上一年的列为 1 时,我想将下面的所有 0 列重新编码为 1。

从这个数据框开始:

library(tibble); library(dplyr)

(df <- tibble(id = c(1,2,3),
       `1997` = c(1,0,0), 
       `1998` = c(0,1,0), 
       `1999` = c(0,0,1)))
#> # A tibble: 3 x 4
#>      id `1997` `1998` `1999`
#>   <dbl>  <dbl>  <dbl>  <dbl>
#> 1     1      1      0      0
#> 2     2      0      1      0
#> 3     3      0      0      1

以这个数据框结束:

tibble(id = c(1,2,3),
       `1997` = c(1,0,0), 
       `1998` = c(1,1,0), 
       `1999` = c(1,1,1))
#> # A tibble: 3 x 4
#>      id `1997` `1998` `1999`
#>   <dbl>  <dbl>  <dbl>  <dbl>
#> 1     1      1      1      1
#> 2     2      0      1      1
#> 3     3      0      0      1

有没有办法用dplyrmutate_at/mutate_if 函数来做到这一点?

我需要一种方法来仅选择年份列,找到值为 1 的最小年份列,并根据该结果改变所有较大的年份列。

# Method that uses dplyr::mutate_at?
# df %>% mutate_at(vars(`1997`:`1999`), funs(replace(., . == 0 & previousColumnVar == 1, 1)))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你可以试试:

    library(tidyverse)
    
    df %>%
      gather(key, value, -id) %>%
      group_by(id) %>%
      mutate(value = +(cumsum(value) >= 1)) %>%
      spread(key, value)
    

    这给出了:

    ## A tibble: 3 x 4
    ## Groups:   id [3]
    #     id `1997` `1998` `1999`
    #  <dbl>  <int>  <int>  <int>
    #1     1      1      1      1
    #2     2      0      1      1
    #3     3      0      0      1
    

    【讨论】:

    • 这看起来会很好用,谢谢。我能麻烦您解释一下+ 语法的用法吗?
    • @ddheart 它将TRUEFALSE 转换为10
    • 我有一个额外的特殊情况,我必须使用一个列StartYear,它定义了一个特定的计数位置,而不是目前的仅取最低年份的方法。是否有一种明显的方法可以重现您使用特定情况编写的内容,其中数据框改为 (df &lt;- tibble(id = c(1,2,3), '1997' = c(1,0,0), '1998' = c(0,1,0), '1999' = c(0,0,1), StartYear = c('1997', '1998', '1999'))) ? (反引号与 SO 降价的引号交换)
    • @ddheart 同样的逻辑适用:df %&gt;% gather(key, value, -id, -StartYear) %&gt;% group_by(id) %&gt;% mutate(value = +(key &gt;= StartYear)) %&gt;% spread(key, value)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2021-08-31
    • 1970-01-01
    • 2014-01-28
    • 2021-12-20
    • 2021-12-05
    • 2016-07-20
    相关资源
    最近更新 更多