Search code examples
rdplyrexpss

table is not generating while rounding the the values


I am trying to create the summary below but while creating the summary the sub function roundval is giving the error for tabl1 else tabl2 is working fine.

I cant change the data , i have to deal with NA so what should i update in function perc_75 to get the output of tab1


library(expss)

dat <- data.frame(cc=c("AMB","CCU","DDI","GLL","MNA","KMB","LTI","DDI","GLL","MNA","CCU","AMB","KMB","LTI","DDI","CCU","GLL"),
                     duration=c(1,NA,66,NA,5,NA,3,1,NA,21,NA,25,NA,17,NA,NA,6),
                     duration2=c(1,4,66,5,5,11,3,1,6,21,54,25,12,17,9,8,6))


roundval <- function (x) 
{
  
  ifelse(round(abs(x - trunc(x)), 1) == 0.5, trunc(x + 0.5), 
         round(x))
}

perc_75 <- function(x) roundval(quantile(x,type = 6,probs = seq(0,1, 0.25),na.rm = TRUE))[4]


tabl1 <- cross_fun(
  dat,
  dat$duration,
  col_vars = dat$cc,
  fun = combine_functions(
    `75th Perc` = perc_75,
    `Valid N` = valid_n
  )
)

tabl2 <- cross_fun(
  dat,
  dat$duration2,
  col_vars = dat$cc,
  fun = combine_functions(
    `75th Perc` = perc_75,
    `Valid N` = valid_n
  )
)

below is the error i am getting

Error in [.data.table(raw_data, , fun(.SD), by = by_string) : Column 1 of result for group 2 is type 'integer' but expecting type 'double'. Column types must be consistent for each group.


Solution

  • You can change roundval so it returns integer values:

    roundval <- function (x) 
    {
        
        ifelse(round(abs(x - trunc(x)), 1) == 0.5, as.integer(trunc(x + 0.5)), 
               as.integer(round(x)))
    }