Error in Mutate (Continuation from Loop 5 Value into 1 problem)

Continuing the discussion from Creating a program that loops 5 values into a mean in one row and places it into a new row repeatedly:

With regard to the previous discussion I'm using the first solution from AlexisW to solve this problem in my full data set. Although after I pivot my data frame and try to create a column of indexes and use that to select every fifth measurement, I get the error seen in the screenshots. Can anyone suggest a potential solution? I don't know why it is off 4 values (must be size 3264 or 1, not 3260)


It appears the number of rows in the tibble is not a multiple of 5, hence the error. Another option would be to use modular arithmetic via row numbers to repeat 1-5 in a new index column. Below is an example of how to do that (note the number of rows is not a multiple of 5).

library(tidyverse)

df = data.frame(id = letters[1:12])

out = df |>
  mutate(index = ifelse(row_number() %% 5 == 0, 
                        5, 
                        row_number() %% 5))

out
#>    id index
#> 1   a     1
#> 2   b     2
#> 3   c     3
#> 4   d     4
#> 5   e     5
#> 6   f     1
#> 7   g     2
#> 8   h     3
#> 9   i     4
#> 10  j     5
#> 11  k     1
#> 12  l     2

If you just want to select every fifth row, then you can do the following.

df |>
  filter(row_number() %% 5 == 0)
#>   id
#> 1  e
#> 2  j

Created on 2023-04-17 with reprex v2.0.2

2 Likes

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.