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

如何在for循环中使用tapply()并在R中打印输出?,r,for-loop,tapply,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) 让世界转动。然而,您的问题是您的代码在语法上是无效的。如果要将所有内容放在一行中,则需要用分

我正在使用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)
让世界转动。然而,您的问题是您的代码在语法上是无效的。如果要将所有内容放在一行中,则需要用分号分隔命令:
。或者,把它们放在两条不同的线上。两个例子:

> 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
>x代表(i进1:3){out代表(i进1:3){

+我还建议避免使用预定义的R函数作为变量名,例如
t
。此外,编写代码的方式是每次都会覆盖
t
,这可能是您所认为的情况,也可能不是您所认为的情况。如果您希望
t
具有与for循环相同的维度,则需要预先分配t检查
t
的维度,然后用适当的索引反复填充
t
> 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