R 关于将sappy索引传递给函数的问题
我相信这是一个简单的问题。但我是编程新手,所以我很挣扎。我认为我试图实现的目标应该从代码中非常清楚。本质上,我想生成一个长度为I的随机数向量,检查是否有小于I的唯一数。我想做很多次,作为一种模拟。当我这样做时,我会手动使用以下代码:R 关于将sappy索引传递给函数的问题,r,function,loops,sapply,R,Function,Loops,Sapply,我相信这是一个简单的问题。但我是编程新手,所以我很挣扎。我认为我试图实现的目标应该从代码中非常清楚。本质上,我想生成一个长度为I的随机数向量,检查是否有小于I的唯一数。我想做很多次,作为一种模拟。当我这样做时,我会手动使用以下代码: experiment<- function() { ab <- rdunif(i, 1, 365) ab <- data.frame(ab) count <- uniqueN(ab)
experiment<- function() {
ab <- rdunif(i, 1, 365)
ab <- data.frame(ab)
count <- uniqueN(ab)
if (count < i)
return(1)
else
return(0)
}
vector <- replicate(10, experiment(), simplify=FALSE)
sum <- sum(as.data.frame((vector)))
probability <- sum/(10)
实验我想出来了:
experiment<- function(i) {
ab <- rdunif(i, 1, 365)
count <- length(unique(ab))
if (count < i) return(1)
else return(0)
}
i <- 10:50
replication <- function(i) {
replicate(100, experiment(i))
}
data<- sapply(i, replication)
colMeans(data)
experiment不确定uniqueN函数是什么,但其余部分看起来像R。R unique函数返回一个向量,而不是标量(唯一值)。因此,错误只是告诉您,experience()的返回值是从count数组的第一个值中选择的(b/c它还能做什么?)。使用sapply()
时替换count,其FUN
参数只是函数名,即需要像sapply(i,complete,simplify=FALSE)那样调用它。
1: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
2: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
3: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
4: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
5: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
6: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
7: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
8: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
9: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
10: In if (count < i) return(1) else return(0) :
the condition has length > 1 and only the first element will be used
experiment<- function(i) {
ab <- rdunif(i, 1, 365)
count <- length(unique(ab))
if (count < i) return(1)
else return(0)
}
i <- 10:50
replication <- function(i) {
replicate(100, experiment(i))
}
data<- sapply(i, replication)
colMeans(data)