识别跨列的特定事件以创建新变量

时间:2018-08-08 07:57:08

标签: r function if-statement sum

我有一个如下数据集

*args

我要创建一个新列,以识别数字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 何时出现在1sh1之间的两个或多个连续列中。如果识别出此模式,则需要总结该模式发生了多少次。

我追求的输出应如下所示:

sh5

任何帮助都是很棒的。

谢谢

3 个答案:

答案 0 :(得分:3)

这是rle函数的经典案例。

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

答案 1 :(得分:1)

一种选择是将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

答案 2 :(得分:0)

您可以执行以下操作:

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