Adding a column that repeats consecutive numbers (1-6)

Hello!

I would like to create a new column that repeats the numbers 1-6 for each subject. The numbers correspond to trials in a block.

I would like something that looks like this:

subj trial_index trial
1 103 1
1 106 2
1 109 3
1 112 4
1 115 5
1 118 6
1 121 1
1 124 2
1 127 3
1 130 4
1 133 5
1 136 6
.....
2 103 1
2 106 2
2 109 3

What would be a good way to do this? Many thanks!

group_by(iris,
         Species) %>% mutate(
       rowrepeats = (row_number()-1) %% 6 +1) %>% ungroup()

# # A tibble: 150 x 6
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species rowrepeats
# <dbl>       <dbl>        <dbl>       <dbl> <fct>        <dbl>
# 1           5.1         3.5          1.4         0.2 setosa           1
# 2           4.9         3            1.4         0.2 setosa           2
# 3           4.7         3.2          1.3         0.2 setosa           3
# 4           4.6         3.1          1.5         0.2 setosa           4
# 5           5           3.6          1.4         0.2 setosa           5
# 6           5.4         3.9          1.7         0.4 setosa           6
# 7           4.6         3.4          1.4         0.3 setosa           1
# 8           5           3.4          1.5         0.2 setosa           2
# 9           4.4         2.9          1.4         0.2 setosa           3
# 10          4.9         3.1          1.5         0.1 setosa           4

Hello! Thank you. I tried running the code with my data, but I seem to only receive 1s in the new column.

This is the code I ran, is it correct?

df = df %>%
  group_by(subj, trial_index) %>%
  mutate(rowrepeat = (row_number()-1) %% 6 +1) %>%
  ungroup()

i think you should remove trial index from the group by, as they seem like unique identifiers on their own account ?

1 Like

Ah thank you, that fixed it!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.