Reputation: 51
Hi I have a data set like this
df <- cbind(c("id",1,2,3,4,5,6,7,8,9,10,11), c("trial",1,1,1,1,1,1,2,2,2,2,2))
However, I want to change the ids conditional on the trial number - something like this
df1 <- cbind(c("id",1.1,1.2,1.3,1.4,1.5,1.6,2.1,2.2,2.3,2.4,2.5), c("trial",1,1,1,1,1,1,2,2,2,2,2))
I would really appreciate it if someone could help me with this. I am still learning R.
Upvotes: 0
Views: 41
Reputation: 8127
df <- data.frame(id = c(1,2,3,4,5,6,7,8,9,10,11), trial = c(1,1,1,1,1,1,2,2,2,2,2))
library(dplyr)
df |>
arrange(trial, id) |>
group_by(trial) |>
mutate(trial_id = row_number()) |>
ungroup() |>
mutate(id = as.numeric(paste0(trial, ".", trial_id)))
# OR use: tidyr::unite("id", c(trial, trial_id), sep = ".", remove = FALSE)
# A tibble: 11 × 3
id trial trial_id
<dbl> <dbl> <int>
1 1.1 1 1
2 1.2 1 2
3 1.3 1 3
4 1.4 1 4
5 1.5 1 5
6 1.6 1 6
7 2.1 2 1
8 2.2 2 2
9 2.3 2 3
10 2.4 2 4
11 2.5 2 5
Upvotes: 2