0

I have a poorly formatted time series dataset in which a single column contains all time series consecutively, and another column contains the trial number.

Example:

Trial Fx
1 7.9
1 8.0
1 8.1
1 8.2
2 6.5
2 6.6
2 6.7
2 6.8

The ultimate goal is to apply signal::filtfilt() to each time series; however, each time series must be filtered separately for this to work appropriately.

I attempted group_by() prior to filtfilt() which resulted in an error. Therefore, I'd like to spread the time series (Fx) into multiple columns by trial so I can filter each column separately, something like this:

Fx_1 Fx_2
7.9 6.5
8.0 6.6
8.1 6.7
8.2 6.8
user438383
  • 5,716
  • 8
  • 28
  • 43
mkp
  • 51
  • 6

1 Answers1

0

You can use pivot_wider from tidyverse to accomplish this. I added an index using group_by and row_number. Then, I remove this column after pivoting wider.

library(tidyverse)
  
df %>%
  group_by(Trial) %>% 
  mutate(grouped_id = row_number()) %>%
  pivot_wider(names_from = Trial,
              values_from = Fx,
              names_prefix = "Fx_") %>%
  select(-grouped_id)

Output

# A tibble: 4 × 2
   Fx_1  Fx_2
  <dbl> <dbl>
1   7.9   6.5
2   8     6.6
3   8.1   6.7
4   8.2   6.8

Data

df <-
  structure(list(
    Trial = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
    Fx = c(7.9, 8, 8.1, 8.2, 6.5, 6.6, 6.7, 6.8)
  ),
  class = "data.frame",
  row.names = c(NA,-8L))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49