简体   繁体   中英

R: Error in get(as.character(FUN), mode = “function”, envir = envir) :

I am working with R. I am trying to replicate the answer provided from this stackoverflow post over here: How can I plot 3D function in r?

Using the "lattice" library in R, I am trying to create a 3D surface plot of "input_1", "input_2", "input_3" - and color the surface according to values of "final_value".

I created a function for this problem:

my_function_b <- function(input_1, input_2, input_3, input_4) {
    
    final_value = sin(input_1) + cos(input_2) + input_3 + input_4
    
}

Then, I assigned each "input" from this function a series of values:

input_1 <- seq(-10, 10, length= 30)
input_2 <- input_1
input_3 <- input_1
input_4 <- input_1

Next, I try to use the "outer" function:

z <- outer(input_1, input_2, input_3, my_function_b)

But this returns the following error:

Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'input_3' of mode 'function' was not found

Can someone please show me what I am doing wrong?

Thanks

Additional References:

outer takes only two arguments. We may need pmap

library(purrr)
pmap_dbl(list(input_1, input_2, input_3, input_4), my_function_b)

or Map/mapply

mapply(my_function_b, input_1, input_2, input_3, input_4)

If we need all combinations, create the combinations with expand.grid and apply over the rows

tmp <- expand.grid(input_1 = input_1, input_2 = input_2, 
     input_3 = input_3, input_4 = input_4)
out <- apply(tmp, 1, 
       FUN = function(x) do.call(my_function_b, as.list(x)))

Or may speed up with dapply from collapse

library(collapse)

out1 <- dapply(tmp, MARGIN = 1, FUN = function(x) 
            my_function_b(x[1], x[2], x[3], x[4]))

Perhaps, we create the combinations on two vectors, and then add ?

my_function_b <- function(input_1, input_2) sin(input_1) + cos(input_2)
tmp1 <- outer(input_1, input_2, my_function_b)
z <- tmp1 + input_3[col(tmp1)] + input_4[col(tmp1)]
library(lattice)
wireframe(z, drape=TRUE, col.regions=rainbow(100))

-output

在此处输入图片说明

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