Different functions over a list of columns and generate new column names automatically with data.table

后端 未结 2 1563
遥遥无期
遥遥无期 2021-01-22 00:45

I have a section in my Shiny app that generates a list.

names of the list are column names of the dataframe we will calculate on, list items contain the ca

2条回答
  •  隐瞒了意图╮
    2021-01-22 01:22

    To turn Uwe's answer into a function I did this:

    Summarystats <- function(statlist, dataframe, group) { 
        statlist %>%
            names() %>% 
            lapply(
                function(.col) lapply(
                    statlist[[.col]], 
                    function(.fct) sprintf("%s.%s = %s(%s)", .col, .fct, .fct, .col))) %>% 
            unlist() %>% 
            paste(collapse = ", ") %>% 
            sprintf("as.data.table(dataframe)[, .(%s), by = group]", .) %>% 
            parse(text = .) %>% 
            eval()
        }
    

    Now I can call:

    Summarystats(mylist, mtcars, 'cyl')
    

    allowing me to call a summary table for whichever dataframe and grouping the user wants in my Shiny App.

提交回复
热议问题