1

I have a dataframe similar to this (although more complex):

id <- rep(1:2, each = 4)
Cond <- rep(c("test", "test","form", "form", "form", "form", "test","test"))

df <- data.frame(id,Cond)

I would like to create a third variable in my dataframe that tells me the order of Cond for each ID. For example, the first participants had first the test and then the form. In the end, the dataframe would look like this:

 id Cond order
  1 test test-form
  1 test test-form
  1 form test-form
  1 form test-form
  2 form form-test
  2 form form-test
  2 test form-test
  2 test form-test

Any help would be much appreciated

1 Answer 1

1

We can check the first element of each 'id' to paste the 'form' or 'test'

library(dplyr)
library(stringr)
df %>% 
    group_by(id) %>%
    mutate(order = str_c(first(Cond), setdiff(c('form', 'test'), 
               first(Cond)), sep='-'))
# A tibble: 8 x 3
# Groups:   id [2]
#     id Cond  order    
#  <int> <fct> <chr>    
#1     1 test  test-form
#2     1 test  test-form
#3     1 form  test-form
#4     1 form  test-form
#5     2 form  form-test
#6     2 form  form-test
#7     2 test  form-test
#8     2 test  form-test
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your reply. Unfortunately, that code doesn't give you the output that I want. For example, for the id 1, your ouput gives this sequence test-form, test-form, form-test, form-test. And for this particpants all should be test-form

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.