简体   繁体   中英

how can I pass elements in a vector to a function as parameters in R?

I would like to pass a vector as part of parameter of a function.

Here is the toy sample, please advise.

func <- function(a, b, c) {sum(a, b, c)}

func(1,2,3)
# [1] 6

# vector of parameters
x = c(1, 2)

func(x, 3)
# Error in func(x, 3) : argument "c" is missing, with no default

func(unlist(x), 3)
# Error in func(unlist(x), 3) : argument "c" is missing, with no default

func(x[1], x[2], 3)
# 6

mapply(func, c(x, 3)) # Not working
mapply(func, c(unlist(x), 3)) # Not working
mapply(func, unlist(x), 3) # Not working
mapply(func, x[1], x[2], 3) # Working but more complicated

Since the parameter vectot could be very long and complicated in real case, how can I make it easier? Thanks for advice.

UPDATE

do.call way is working at plain case. At my real case, I am treating something like this.

library(keras)
imDim = c(150, 150)
input <- layer_input(shape = c(imDim[1], imDim[2], 3)

in do.call method, it shall become, input <- do.call(layer_input, as.list(c(imDim,3)) . seems not less complicated.

Or in other case,

# toy example: a is an input layer 
Layer1 <- layer_conv_2d(filters = 32, kernel_size = c(3, 2), 
          activation = "relu", input_shape = c(150, 150, 3))

# what if the dimension of image may change, the flexibility shall be there.
Shape <- c(150, 150)

# to make the code readable, 
# I set a function to accept parameters coming from do.call.

LayerFunc <- function(p, q) {layer_conv_2d(filters = 32, 
             kernel_size = c(3, 2), activation = "relu", 
             input_shape = c(p, q, 3))}

# pass parameter with do.call 
Layer2 <- do.call(LayerFunc, as.list(c(Shape)))

# however Layer1 & Layer2 are different, 
# besides, the do.call way seems more complicated

identical(a, d)
#> Layer1
#<tensorflow.python.keras.layers.convolutional.Conv2D>
#> Layer2
#<tensorflow.python.keras.layers.convolutional.Conv2D>
#> identical(Layer1, Layer2)
[1] FALSE

If you print the value of a you'll realise what is happening in the function.

func <- function(a, b, c) print(a)

func(1, 2, 3)
#[1] 1

x = c(1, 2)
func(x, 3)
#[1] 1 2

So in the second example both 1, 2 are considered as a and not a and b as you expected.

To overcome this one way would be to pass list of arguments to the function with the help of do.call .

do.call(func, as.list(c(x, 3)))
#[1] 1

Change to the original function.

func <- function(a, b, c) sum(a, b, c)
do.call(func, as.list(c(x, 3)))
#[1] 6

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