Issue with replicate

Hi, i have an issue and I hope sombody can help me out with my coding.

I have e.g. following code:

Col1 <- c(1,2,3,4,5,6,7,8,9,10)
Col2 <- c(0,0.1, 0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)

colnames(Sampling_var)[1:4]

Sampling <- matrix(ncol=4, nrow=10)
Data <- data.frame(Col1,Col2)


op <- function(){
  n <- qpois(runif(1), 3,5)
  z <- replicate(n, {Data[match.closest(runif(1),Data$Col2),1]})
  sum(z)}

for (x in 1:10) {
  Loss <- replicate(5000, op())
  
  Sampling[x,1] <- quantile(Loss, 0.975)
  Sampling[x,2] <- quantile(Loss, 0.990)
  Sampling[x,3] <- quantile(Loss, 0.999)
  Sampling[x,4] <- mean(Loss)
  
}

If i run this code I'll get this error message: error in sum(z) invalid 'type' (list) of argument

I would be grateful if sombody could explain to me what I am droing wrong : )

Cheers

The issue is in this line:

The error occurs if n = 0, as replicate in that case will result in an empty list.

Hope that answers your question.

(Sorry, I can't suggest a solution as I didn't understand what you are trying to do. May be someone else will help with that.)

1 Like

Hi Yarnabrina!

You don't have to be sorry, I am very grateful for your help : ) Thank you so much! Because of your help I fixed it by this type of code:

op <- function(){
  n <- qpois(runif(1), 2)
  z <- if(length(replicate(n, {Data[match.closest(runif(1),Data$Col2),1]})) == 0) {0} else { 
        replicate(n, {Data[match.closest(runif(1),Data$Col2),1]})}
  sum(z)}

: )

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.