0

i would like to get a new variable lastocc with the values 1 and 2. the variable lastocc should show for each word if its last occurrence was shown also in the same color or not.

So, in case when the particular word was shown now and previous time in the same color, it should be coded as 1. if in its last occurrence it was shown in difference color , it should be coded 2.

for example:

trial      word   color  lastocc
1          warm   red
2          klein  blue
3          ganz   yellow
4          warm   red      1
5          klein  red      2 
6          ganz   yellow   1
7          klein  red      1    

i tried this code and its not working:

data_expblocks$lastocc <- if (data_expblocks$word == TRUE & data_expblocks$color == TRUE) {lastocc = 1}  
 else { lastocc =2 }

hier is dput() =

structure(list(Subject = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L), Word = c("XXXX", "XXXX", "warm", "klein", "klein", "warm", 
"ganz", "warm", "leicht", "ganz"), Colour = c("YELLOW", "RED", 
"RED", "RED", "RED", "RED", "RED", "YELLOW", "RED", "YELLOW")), row.names = 53:62, class = "data.frame")

would be nice if you can advise me something. thank you!

1 Answers1

0

Here is one approach using dplyr package.

First, use group_by to look at each word for a given subject. The only difference between rows should be the Colour.

Then, you can use mutate to create a new column. Using ifelse is will evaluate if the Colour for a given row is the same as the previous Colour. If it is, then the value will be 1. If not, it will be 2. If there is no prior value available (first time word appears), it will be NA.

library(dplyr)

data_expblocks %>%
  group_by(Subject, Word) %>%
  mutate(lastocc = ifelse(Colour == lag(Colour), 1, 2))

Output

   Subject Word   Colour lastocc
     <int> <chr>  <chr>    <dbl>
 1       1 XXXX   YELLOW      NA
 2       1 XXXX   RED          2
 3       1 warm   RED         NA
 4       1 klein  RED         NA
 5       1 klein  RED          1
 6       1 warm   RED          1
 7       1 ganz   RED         NA
 8       1 warm   YELLOW       2
 9       1 leicht RED         NA
10       1 ganz   YELLOW       2
Ben
  • 28,684
  • 5
  • 23
  • 45