我有一个与此类似的数据框(尽管更复杂):
id <- rep(1:2, each = 4)
Cond <- rep(c("test", "test","form", "form", "form", "form", "test","test"))
df <- data.frame(id,Cond)
我想在数据框中创建第三个变量,该变量告诉我每个ID的Cond顺序。例如,第一个参与者首先拥有测试,然后是表单。最后,数据框将如下所示:
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
任何帮助将不胜感激
答案 0 :(得分:1)
我们可以检查每个'id'的第一个元素,以paste
的形式或测试'
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