Home > other >  R language - Creating a function and array out of it
R language - Creating a function and array out of it

Time:01-26

I need to create a function in R called "Zufall(n,max)" which returns "n" random integers between "1" and "max"(max is an argument to the function and not a the function max()!!). Integers can appear repeatedly.

Zufall <- function(n,mx){
Zahl <- 1:mx  
if(!is.double(n)) stop("Geben sie eine ganzzahlige Zahl ein!")
  if(Zahl>mx) stop("Geben sie eine ganzzahlige Zahl ein!")
  else sample(n,replace=T)
}
  1. My problem ist that the "mx" is ignored by the code - i generate values higher than the mx-value! E.g. when I enter "Zufall(1000,8)", I generate the integer "719" ... that should not be the case; numbers shall stop at "8" in this case!
  2. How do I best create an array of dimension 2x3x4 out of it?

Thank you very much ..appreciating your helb!

CodePudding user response:

simply:

sample(1:mx, n, replace = TRUE)

for instance sample(1:8, 1000, replace = TRUE).

Your condition if(Zahl>mx) is wrong since Zahl is a vector of length > 1, anyway this test is useless since by construction 1:mx will not generate any number > mx

  •  Tags:  
  • Related