问题
I am using tapply() to apply a function to my data
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)
I would like to use this within a for loop and print out the output. I have tried the following and I get the error message: 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:
Reproducible examples make the world go round. However, your problem is that your code is not syntactically valid. If you want to put everything on a single line, you need to separate the commands by a semicolon: ;
. Or, put them on two different lines. Two 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
来源:https://stackoverflow.com/questions/10687543/how-to-use-tapply-within-a-for-loop-and-print-output-in-r