Reputation: 145
I have a data.frame as such.
data.frame(color = c("G","G","G","R","R","R","R","R","R","R","G","G"),
trial = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4))
I want to detect when the color
switches for each 'trial'. Like this:
color trial swtch
1 G 1 0
2 G 1 0
3 G 1 0
4 R 2 1
5 R 2 1
6 R 2 1
7 R 3 0
8 R 3 0
9 R 3 0
10 R 3 0
11 G 4 1
12 G 4 1
I know how to accomplish this with a for
loop. But is there a simple way to accomplish this in R. I thought maybe the ave
function would be useful.
Upvotes: 1
Views: 68
Reputation: 93813
Here's something a little different:
x <- interaction(dat,drop=TRUE)
x <- factor(x, levels=unique(x))
levels(x)[] <- 0:1
dat$swtch <- x
# color trial swtch
#1 G 1 0
#2 G 1 0
#3 G 1 0
#4 R 2 1
#5 R 2 1
#6 R 2 1
#7 R 3 0
#8 R 3 0
#9 R 3 0
#10 R 3 0
#11 G 4 1
#12 G 4 1
Upvotes: 3
Reputation: 886948
We can use ave
by creating a logical index of comparing the adjacent elements of 'color', grouped by 'trial', and get the cummax
.
with(df1, ave(c(FALSE,color[-1]!= color[-nrow(df1)]),
trial, FUN= cummax))
#[1] 0 0 0 1 1 1 0 0 0 0 1 1
Upvotes: 1