【问题标题】:Recognising specific occurrences across columns to create a new variable识别跨列的特定事件以创建新变量
【发布时间】:2019-01-15 09:47:55
【问题描述】:

我有一个如下所示的数据集

year  sh1  sh2  sh3  sh4  sh5
2011   0    1    1    0    0
2012   1    1    0    1    1
2013   0    0    0    0    0
2014   1    1    0    0    0
2015   1    1    1    1    1

我希望创建一个新列,以识别数字 1 何时出现在 sh1sh5 之间的两个或多个连续列中。如果识别出这种模式,则需要总结该模式出现的次数。

我所追求的输出应该是这样的:

year  sh1  sh2  sh3  sh4  sh5  newVariable
2011   0    1    1    0    0        1
2012   1    1    0    1    1        2
2013   0    0    0    0    0        0
2014   1    1    0    0    0        1
2015   1    1    1    1    1        1

任何帮助都会很棒。

谢谢

【问题讨论】:

  • 我投了赞成票,因为你做了一个很好的例子,你的数据涵盖了“所有”可能的情况!
  • 非常感谢

标签: r function if-statement sum


【解决方案1】:

这是rle函数的经典案例。

apply(df[-1], 1, function(i){r1 <- rle(i); sum(r1$lengths[r1$values == 1] >= 2)})
#[1] 1 2 0 1 1

【讨论】:

  • 总是忘记rle 的强大和普遍。
【解决方案2】:

一个选项是 pastedo.call 然后用正则表达式环视计算连续 1 的数量

library(stringr)
df$new_variable <-  str_count(do.call(paste0, df1[-1]), "(?<=1)1+")
df$new_variable
#[1] 1 2 0 1 1

【讨论】:

    【解决方案3】:

    你可以这样做:

    library(magrittr)
    df1$newVariable <-
    df1[,-1] %>% apply(1,paste0,collapse="") %>% stringr::str_count("^11|011")
    
    #  year sh1 sh2 sh3 sh4 sh5 newVariable
    #1 2011   0   1   1   0   0           1
    #2 2012   1   1   0   1   1           2
    #3 2013   0   0   0   0   0           0
    #4 2014   1   1   0   0   0           1
    #5 2015   1   1   1   1   1           1
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2015-09-24
      • 2019-10-01
      相关资源
      最近更新 更多