如何在for循环中使用tapply()并在R中打印输出?

时间:2012-05-21 14:49:34

标签: r for-loop tapply

我正在使用tapply()将函数应用于我的数据

Myrepfun <- function(x,n){
    nstudents <- replicate(1000,sum(sample(x, size=n,replace=TRUE)))
    quantile(nstudents,probs=0.95)
}

tapply(weight,schoolcode,Myrepfun,n=2)

我想在for循环中使用它并打印出输出。我尝试了以下操作,并收到错误消息:Error: unexpected symbol in "for(n in 12:13) (t=tapply(ow,sc,ndropfunction,n,p=0.95) output

for(n in 1:25) {t=tapply(weight,schoolcode,Myrepfun,n,p=0.95) print(c=(t,n))}

1 个答案:

答案 0 :(得分:2)

Reproducible examples让世界变得圆满。但是,您的问题是您的代码在语法上无效。如果要将所有内容放在一行上,则需要用分号分隔命令:;。或者,将它们放在两条不同的线上。两个例子:

> x <- runif(100)
> for (i in 1:3){out <- mean(x);print(c(out,i))}
#-----
[1] 0.4958944 1.0000000
[1] 0.4958944 2.0000000
[1] 0.4958944 3.0000000
> for (i in 1:3){
+   out <- mean(x)
+   print(c(out,i))
+ }
#-----
[1] 0.4958944 1.0000000
[1] 0.4958944 2.0000000
[1] 0.4958944 3.0000000