如何在for循环中使用tapply()并在R中打印输出? [英] How to use tapply() within a for loop and print output in R?

查看:175
本文介绍了如何在for循环中使用tapply()并在R中打印输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  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循环内并打印出输出。我已经尝试了以下,并得到错误消息:错误:意外符号在for(n 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))} 


解决方案

可复制的例子使世界去但是,你的问题是你的代码在语法上是不合法的,如果你想把所有东西放在一行上,你需要用分号分隔这些命令:; 或者把它们放在两行不同的行上,两个例子:

$ $ p $ > x < - runif(100)$ b $ (x); print(c(out,i))}
#-----
[1] 0.4958944 1.0000000
[1] 0.4958944 2.0000000
[1] 0.4958944 3.0000000 $ b $ gt; 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


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))}

解决方案

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

这篇关于如何在for循环中使用tapply()并在R中打印输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆