How to a run function per group that return vector, not single value?

前端 未结 2 1526
傲寒
傲寒 2021-01-22 20:41

I have a dataset data.frame(x=rnorm(100),group=c(rep(\'a\',40),rep(\'b\',60))) that I want to analyse per group with dplyr. For example I want to use a fft

相关标签:
2条回答
  • 2021-01-22 20:54

    We can do with unnest after creating a list output with summarise. It would be more easier to work with

    library(tidyverse)
    df1 %>%
        group_by(group) %>%
        summarise(value = list(fft(x))) %>%
        unnest()
    
    0 讨论(0)
  • 2021-01-22 21:11

    There are essentially three options:

    1. If you want to create a single summary value per group, use summarize.
    2. If you want to transform each value per group, use mutate.
    3. If you want to create a new table per group, use do.

    The last option seems to fit your purpose best, if I understood you correctly. do is generally the most powerful of these options, but also the hardest to use. The general syntax is:

    data %>%
        group_by(grouping_cols) %>%
        do(data_frame(col1 = some_transformation(.$x)))
    

    For example:

    iris %>%
        group_by(Species) %>%
        do(broom::tidy(lm(Sepal.Length ~ Sepal.Width, data = .)))
    
    0 讨论(0)
提交回复
热议问题