Search code examples
rellipsisfunction-callfunction-parameter

Send "unclassed" variabel as function parameters?


or

How to create my own '...' variable?

Functions often return a specific structure (or class). Sometimes the parameters of the function also are apart of the returning structure. After manipulating the result, how can I send it as the parameters to a function (or the same function again)?

Very short pseudo-example:

res1 <- power.t.test(alot of parameters)
res1b <- res1
res1b$some.parameter <- new-value
res2 <- power.t.test(parameters = unclass(res1b))

This is a general question, that I stumbled upon when trying to solve a specific problem. I include the code to, hopefully, clearify my question:

set.seed(42); data <- rnorm(20) #to be able to reproduce

# Calculate how many pairs I need to find a difference of 1 ----
ptt1 <- power.t.test(delta = 1, sd = sd(data), sig.level = 0.05, power = 0.8, type = "paired", alternative = "two.sided")
# Paired t test power calculation
# 
# n = 15.55315
# delta = 1
# sd = 1.312628
# sig.level = 0.05
# power = 0.8
# alternative = two.sided
# 
# NOTE: n is number of *pairs*, sd is std.dev. of *differences* within pairs

# However, I wishing to know the exact power when changing n to next greater integer ----
ptt1$n <- ceiling(ptt1$n)
ptt1$power <- NULL
unclass(ptt1)
# $n
# [1] 16
# $delta
# [1] 1
# $sd
# [1] 1.312628
# $sig.level
# [1] 0.05
# $alternative
# [1] "two.sided"
# $note
# [1] "n is number of *pairs*, sd is std.dev. of *differences* within pairs"
# $method
# [1] "Paired t test power calculation"

# This is a solution ----
power.t.test.power <- function(ptt) {
  power.t.test(n = ceiling(ptt$n), delta = ptt$delta, sd = ptt$sd, sig.level = ptt$sig.level, type = ptt$type, alternative = ptt$alternative)
}

ptt1$type <- "paired" #power.t.test output (of class "power.htest") misses this named element
power.t.test.power(ptt1)
# Paired t test power calculation 
# 
# n = 16
# delta = 1
# sd = 1.312628
# sig.level = 0.05
# power = 0.8126338
# alternative = two.sided
# 
# NOTE: n is number of *pairs*, sd is std.dev. of *differences* within pairs

# BUT I WISHED that any of this would work, but all gives the same error ----
power.t.test(ptt1)
power.t.test(unclass(ptt1))
power.t.test(unlist(ptt1))
# Error in power.t.test(ptt1) : 
#   exactly one of 'n', 'delta', 'sd', 'power', and 'sig.level' must be NULL


Solution

  • I see you've already accepted another answer, but just for the record:

    do.call is the way to call on a function and pass a list instead of the individual arguments. In this case, it will look like this:

    do.call(power.t.test,as.list(ptt1))
    

    If you only want to pass some of the arguments, you can subset the vector with names that appear in the list of arguments for the function:

    do.call(power.t.test,as.list(ptt1[names(ptt1) %in% formalArgs(power.t.test)]))