Home > OS >  export two tables consecutively with expss like output
export two tables consecutively with expss like output

Time:04-11

I am trying to create a function where i can two tables if the parameter num is TRUE. but its showing only single table in place of two table .

it should show two table when parameter num == TRUE

library(expss)
mtcars = apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors"
)


banner <-  with(mtcars,list(total(), am))

var <- "mpg"
data = mtcars


func1 <- function(data,var,banner,num){

if (num==TRUE) {
 
df1 <- expss::cro_cpct(data[[var]],banner)
df2 <- cross_fun(data,
          data[[var]],
          col_vars = banner,
          row_vars = vs,
          fun = combine_functions(Mean = mean,
                                  'Std. dev.' = sd,
                                  'Valid N' = valid_n))
      df1
      df2
}else{
  df1 <- expss::cro_cpct(data[[var]],banner)
  df1
             }


}

t1 <- func1(mtcars,"mpg",banner,num=FALSE)

i will export these tables in xlsx file

CodePudding user response:

In R, if you don't explicitly use return() within your functions to return an object, R will return the last object that was called (see here for more information).

In your example, when num == TRUE you are calling d1 THEN d2 so d2 is the last object called and is therefore returned. Functions can only return a single object, so if you want return both tables you need to wrap them together in a list, and then you can return both tables as a single object.

This modification to your function should give you what you want.

func1 <- function(data, var, banner, num){
  if (num==TRUE) {
    df1 <- expss::cro_cpct(data[[var]], banner)
    df2 <- cross_fun(data,
                     data[[var]],
                     col_vars = banner,
                     row_vars = vs,
                     fun = combine_functions(Mean = mean,
                                             'Std. dev.' = sd,
                                             'Valid N' = valid_n))
    return(list(df1, df2))
    
  } else {
    df1 <- expss::cro_cpct(data[[var]], banner)
    return(df1)
  }
}

You can then access df1 and df2 by indexing.

t1 <- func1(mtcars, "mpg", banner,  num=TRUE)
t1[[1]]
t1[[2]]
  •  Tags:  
  • r
  • Related