find point of x contiguous responses
I'm trying to find the point at which participants reach 8 contiguous responses in a row. The data is from a category 开发者_StackOverflow社区learning task so the variable would look like:
R> data
[1] 1 1 1 0 0 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1..
I'm trying to find the trial number at which participants achieved our criterion for learning - 8 correct responses in a row (1 represent a correct response). So i would want to return 18 from the above example, since it's on the 18th trial that the participant reached 8 correct responses in row.
Sorry if this has been answered elsewhere. I looked around fair bit and found a few similar problems but nothing that I could figure out how to directly apply to my problem. I just started using R today (switching from SPSS) so I'm still learning.
Thanks in advance! Let me know if i need to provide more detail.
Setting
x <- c(1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
here are two ways:
1) embed. Using embed
find the first row of 1's as follows:
> which(rowSums(embed(x, 8)) == 8)[1] + 8 - 1
[1] 18
2) rollapply. Its a bit less tricky with the zoo package. With that we take the rolling sum of the last 8 values and then find the time where it first becomes 8:
> library(zoo)
> r <- rollapply(zoo(x), 8, sum, align = "right")
> time(r[r == 8][1])
[1] 18
rle
offers a way to look at lengths of runs. First find all runs equal to or greater than 8 with value == 1. Then sum up all the lengths prior to that and add 8.
> which( rle(x)$values==1 & rle(x)$lengths >= 8)
[1] 5
If there are more than one then take the minimum and subtract one from that for an index:
> sum(rle(x)$lengths[ 1:(min(which(rle(x)$lengths >= 8))-1) ]) + 8
[1] 18
A basic solution with a loop:
check_continous_values <- function(d, n) {
for (i in n:length(d)) {
if (sum(d[(i-(n-1)):i]) == n) return(i)
}
}
See it in action:
> d <- c(1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
> check_continous_values(d,8)
[1] 18
精彩评论