简体   繁体   中英

Setting the names in `…` for an R function

Suppose arguments of function foo are arbitrary defined as ... .

If names of the arguments are a = c("ESL", "prof") , and their values are a1.vales = 1:8 and a2.vales = 0:7 :

how can I make: foo(a[1] = a1.vales, a[2] = a2.vales) to work just like: foo("ESL" = a1.vales, "prof" = a2.vales) ?

PS can setNames help here?

foo <- function(n = 2:9, ...){

  data.frame(n = n, ...)
}

## Function argument names and values:
a = c("ESL", "prof")
a1.vales = 1:8
a2.vales = 0:7

## Example of use: 
foo(a[1] = a1.vales, a[2] = a2.vales)    # Fails?
foo("ESL" = a1.vales, "prof" = a2.vales) # Works

To solve your current problem there exists a workaround:

foo <- function(n = 2:9, ...){
  args <- list(...)
  setNames(data.frame(c(list(n), args[-1])), c("n", args[[1]]))
}

foo(n = 2:9, a, a1.vales, a2.vales)

  n ESL prof
1 2   1    0
2 3   2    1
3 4   3    2
4 5   4    3
5 6   5    4
6 7   6    5
7 8   7    6
8 9   8    7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM