Search code examples
rdplyrtibblesummarize

Summarise with an external variable


I'm trying to make this code work for an external variable:

#This is the original code

library(dplyr)
library(tibble)
nFinal <- 5
graphData <- tibble(y = rep(1:nFinal,2),
                    ponde = runif(10, min = 0, max = 1),
                    )

totalData <- graphData %>%
  **summarise**(val1 = prop.table(questionr::wtd.table(y, weights = ponde))[1]*100,
            val2 = prop.table(questionr::wtd.table(y, weights = ponde))[2]*100,
            val3 = prop.table(questionr::wtd.table(y, weights = ponde))[3]*100,
            val4 = prop.table(questionr::wtd.table(y, weights = ponde))[4]*100,
            val5 = prop.table(questionr::wtd.table(y, weights = ponde))[5]*100)

What I would like is for this to be able to be done for a supplied number of values, so the last val should depend on a number supplied in an external integer nFinal , something like this:


nFinal <- 10 #or any value

totalData <- graphData %>%
  summarise(val1 = prop.table(questionr::wtd.table(y, weights = ponde))[1]*100,
            val2 = prop.table(questionr::wtd.table(y, weights = ponde))[2]*100,
            val3 = prop.table(questionr::wtd.table(y, weights = ponde))[3]*100,
            val4 = prop.table(questionr::wtd.table(y, weights = ponde))[4]*100,
            val5 = prop.table(questionr::wtd.table(y, weights = ponde))[5]*100,
            ... 
          valnFinal = prop.table(questionr::wtd.table(y, weights = ponde))[nFinal]*100)

I'm using dplyr for this but I would accept any other solution.

(edit, made example data have nFinal elements, as pointed out in comment to arkun.)


Solution

  • You may save the output in a list and use unnest_wider to create new columns.

    library(dplyr)
    library(tidyr)
    
    graphData %>%
      summarise(val = list(prop.table(questionr::wtd.table(y, weights = ponde)) * 100)) %>%
      unnest_wider(val)
    
    #   `1`   `2`   `3`   `4`   `5`
    #  <dbl> <dbl> <dbl> <dbl> <dbl>
    #1  37.2  20.0  21.8  12.2  8.92