R 语言 - 从中​​创建函数和数组

R language - Creating a function and array out of it

我需要在 R 中创建一个名为“Zufall(n,max)”的函数,其中 returns“n”个介于“1”和“max”之间的随机整数(max 是函数的参数,不是函数 max()!!)。整数可以重复出现。

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. 我的问题是代码忽略了“mx”——我生成的值高于 mx 值!例如。当我输入“Zufall(1000,8)”时,我生成了整数“719”……但事实并非如此;在这种情况下,数字应停在“8”!
  2. 如何最好地从中创建一个 2x3x4 维度的数组?

非常感谢..感谢您的帮助!

简单地说:

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

例如sample(1:8, 1000, replace = TRUE).

你的条件 if(Zahl>mx) 是错误的,因为 Zahl 是长度 > 1 的向量,无论如何这个测试是无用的,因为通过构造 1:mx 不会生成任何数字 > mx