I have the following data frame:
I have multiple participants listed in subj_id (you can see only 2 here). I want to change all Pre items in the trial column to Pre1, Pre2, Pre3, Pre4.
How can I do this?
I have the following data frame:
I have multiple participants listed in subj_id (you can see only 2 here). I want to change all Pre items in the trial column to Pre1, Pre2, Pre3, Pre4.
How can I do this?
dat <- data.frame(
subj_id = c(rep(1L, 7), rep(2L, 7)),
trial = c(rep("Pre", 4), rep("Test", 3), rep("Pre", 4), rep("Test", 3)),
judgment = 1:14
)
dat
# subj_id trial judgment
# 1 1 Pre 1
# 2 1 Pre 2
# 3 1 Pre 3
# 4 1 Pre 4
# 5 1 Test 5
# 6 1 Test 6
# 7 1 Test 7
# 8 2 Pre 8
# 9 2 Pre 9
# 10 2 Pre 10
# 11 2 Pre 11
# 12 2 Test 12
# 13 2 Test 13
# 14 2 Test 14
ave(seq_len(nrow(dat)), dat[,c("subj_id", "trial")], FUN = seq_along)
# [1] 1 2 3 4 1 2 3 1 2 3 4 1 2 3
dat$trial <- paste0(dat$trial, ave(seq_len(nrow(dat)), dat[,c("subj_id", "trial")], FUN = seq_along))
dat
# subj_id trial judgment
# 1 1 Pre1 1
# 2 1 Pre2 2
# 3 1 Pre3 3
# 4 1 Pre4 4
# 5 1 Test1 5
# 6 1 Test2 6
# 7 1 Test3 7
# 8 2 Pre1 8
# 9 2 Pre2 9
# 10 2 Pre3 10
# 11 2 Pre4 11
# 12 2 Test1 12
# 13 2 Test2 13
# 14 2 Test3 14
If you only need "Pre"
numbered, then alter that code above to be
dat$trial <- ifelse(dat$trial == "Pre", paste0(dat$trial, ave(seq_len(nrow(dat)), dat[,c("subj_id", "trial")], FUN = seq_along)), dat$trial)
dat
# subj_id trial judgment
# 1 1 Pre1 1
# 2 1 Pre2 2
# 3 1 Pre3 3
# 4 1 Pre4 4
# 5 1 Test 5
# 6 1 Test 6
# 7 1 Test 7
# 8 2 Pre1 8
# 9 2 Pre2 9
# 10 2 Pre3 10
# 11 2 Pre4 11
# 12 2 Test 12
# 13 2 Test 13
# 14 2 Test 14
library(dplyr)
dat %>%
group_by(subj_id, trial) %>%
mutate(trial = paste0(trial, row_number())) %>%
ungroup()
# # A tibble: 14 x 3
# subj_id trial judgment
# <int> <chr> <int>
# 1 1 Pre1 1
# 2 1 Pre2 2
# 3 1 Pre3 3
# 4 1 Pre4 4
# 5 1 Test1 5
# 6 1 Test2 6
# 7 1 Test3 7
# 8 2 Pre1 8
# 9 2 Pre2 9
# 10 2 Pre3 10
# 11 2 Pre4 11
# 12 2 Test1 12
# 13 2 Test2 13
# 14 2 Test3 14
Similarly, if only "Pre"
, then
dat %>%
group_by(subj_id, trial) %>%
mutate(trial = if_else(trial == "Pre", paste0(trial, row_number()), trial)) %>%
ungroup()