gpt4 book ai didi

r - R 数据框中先前连续出现的事件

转载 作者:行者123 更新时间:2023-12-04 11:44:05 25 4
gpt4 key购买 nike

我正在尝试编写一个代码,在其中我可以找到相同二进制值的先前连续出现。

我已经设法编写了一个 for 循环来查找以前的值(在我的实际问题中,数据被子集化因此需要一个 for 循环)。

x<-data.frame(successRate=c(1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,1))


xLength<-length(x$successRate)

y<-vector(mode="integer",length<-xLength)

if (xLength>1){

for (i in 2:xLength){
y[i]<-x$successRate[i-1]
}

}

y[1]<-NA

x[,"previous"]<-y

但是我正在寻找如下所需的输出:

# desired output

data.frame(successRate=c(1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,1),previousConsecutiveSuccess=c(NA,1,2,-1,1,-1,-2,-3,1,-1,1,2,3,-1,1,-1,-2,-3,-4,1,2,-1))

最佳答案

x <- data.frame(successRate=c(1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,1))
x$previous <- NA # no need for extra variable

if (nrow(x)>1) {

# set first consecutive idx manually
x$previous[2] <- -1+2*x$successRate[1] # -1 if successRate == 0; 1 otherwise

# loop only if nrow(x) is large enough
if (nrow(x)>2) {
for (i in 3:nrow(x)){ # start on row 3, as the last 2 rows are needed
x$previous[i] <- ifelse(x$successRate[i-1] == x$successRate[i-2], # consecutive?
sign(x$previous[i-1])*(abs(x$previous[i-1])+1), # yes: add 1 and keep sign
-1+2*x$successRate[i-1]) # no: 0 -> -1; 1 -> 1
}
}
}
print(x$previous)

[1] NA 1 2 -1 1 -1 -2 -3 1 -1 1 2 3 -1 1 -1 -2 -3 -4 1 2 -1

关于r - R 数据框中先前连续出现的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com