How to use tapply() within a for loop and print output in R?

僤鯓⒐⒋嵵緔 提交于 2019-12-08 10:52:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!