Search code examples
rdataframegroup-bydata-cleaningmutate

R: Help using group_by( ) then mutate( ) to add a column into the df counting data up


I have a data frame where the data is chunked into blocks of 10 trials. The data frame does not have a "trial_within_block" variable and I want to add one. I have used the following code:

data <- data %>%
  group_by(subject, block) %>%
  mutate(trial_within_block = c(1:10))

And this works great! However, sometimes the subjects did not finish their last block, so sometimes their last block only has 5-9 trials. When this happens, it throws an error saying:

"Error in mutate(): ℹ In argument: trial_within_block = c(1:10). Caused by error: ! trial_within_block must be size 7 or 1, not 10.

Is there a way to count up 1 through 10, but then on blocks that have less than 10, for it to stop?


Solution

  • data <- data %>%
     group_by(subject, block) %>%
     mutate(trial_within_block = 1:length(block))
    

    This should work!