【问题标题】:How to use tapply() within a for loop and print output in R?如何在for循环中使用tapply()并在R中打印输出?
【发布时间】:2012-05-21 14:49:33
【问题描述】:

我正在使用 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))}

【问题讨论】:

  • 我还建议避免使用预定义的 R 函数作为变量名,例如 t。此外,您的代码编写方式是 t 每次都会被覆盖......这可能是您认为发生的事情,也可能不是。如果您希望t 与您的for 循环具有相同的维度,则需要预先分配t 的维度,然后使用适当的索引迭代地填充t

标签: r for-loop tapply


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2015-12-29
    • 2021-12-20
    • 2023-03-11
    相关资源
    最近更新 更多