简体   繁体   中英

Spreading time series data in R by trial

I have a poorly formatted time series dataset in which a single column contains all time series consecutively, and another column contains 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

I'm sure I'm missing something simple. Thank you in advance for the help.

You can use pivot_wider from tidyverse to accomplish this.

library(tidyverse)
  
df %>%
  pivot_wider(names_from = Trial,
              values_from = Fx,
              names_prefix = "Fx_",
              values_fn = list) %>%
  unnest(everything())

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM