简体   繁体   中英

Passing a function as a parameter of another function in R

I'm trying to write a function that proves the Central Limit Theorem in R. It will take a value n and a Probability Density Function as parameters, and returns the mean of 1000 samples of a PDF, n times.

So I have a PDF as a function, like this:

pdf1 <- function() {
  x = runif(1, min=0, max=2)
  if(x <= 1) {
    y = x
  } else {
    y=2-x
  }
  y
}

And I'm trying to use this function as a parameter in my new function that should return the means of 1000 samples from this PDF, n times.

newpdf <- function(n, pdfx) {
  array4 <- c()
  for(i in 1:n) {
    array4 = c(array4, mean(replicate(1000, pdfx)))
  }
  print(array4)
}

This doesn't work. It just returns 1 value n times, like this:

newpdf(10, pdf1())
[1] 0.07446415 0.07446415 0.07446415 0.07446415 0.07446415 0.07446415 0.07446415 0.07446415 0.07446415
[10] 0.07446415

But if I hard code in the PDF, like this:

newpdf <- function(n){
     array4 <- c()
     for(i in 1:n) {
         array4 = c(array4, mean(replicate(1000, pdf1())))
     }
     print(array4)
 }

It gives me exactly the values I want..

> newpdf(19)

[1] 0.4924323 0.5007244 0.4935517 0.5070427 0.4882152 0.5006345 0.5080305 0.4992261 0.5106020
[10] 0.5045957 0.5080413 0.5049816 0.5043062 0.4964958 0.4903163 0.5203326 0.5107542 0.5069920
[19] 0.4921472

So I'm not sure what's going on here. I have no idea why it's not able to understand the PDF as a parameter but it understands it when I hardcode it. Anyway, if somebody can help shed some light on this, that would be awesome!

You shouldn't use parenthesis after pdf1 when calling newpdf , because you're passing the function name, not calling it.

Following the same logic, you should use them inside replicate() .

pdf1 <- function() {
  x = runif(1, min=0, max=2)
  if(x <= 1) {
    y = x
  } else {
    y=2-x
  }
  y
}

newpdf <- function(n, pdfx) {
  array4 <- c()
  for(i in 1:n) {
    array4 = c(array4, mean(replicate(1000, pdfx())))
  }
  print(array4)
}

set.seed(1)
newpdf(19, pdf1)
[1] 0.5027618 0.4827648 0.4943929 0.4750925 0.4948409 0.5177700 0.4982195 0.5003837 0.5011541 0.4884556
[11] 0.5022072 0.4999359 0.4882833 0.4959163 0.5146288 0.4954670 0.5057518 0.5008227 0.5000727

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