【问题标题】:Running simulations: random sampling in a for loop运行模拟:for 循环中的随机抽样
【发布时间】:2019-10-24 05:16:08
【问题描述】:

我正在尝试使用只有 x 和 y 值(为本练习任意组成)的数据集 (TOY) 运行此循环,并且我继续收到第 7 行错误:TOY 中的错误(TD2$x) : 找不到函数“TOY”。我不确定如何解决 R 似乎将 TOY 识别为该行中的函数而不是数据集的事实。它作为 RDS 文件保存在我的工作目录中。任何帮助是极大的赞赏。

set.seed(123)
random.sims<-1000 
n<-50 
results<-c() #empty vector for results
TD2 <- c()
for (i in 1:random.sims) {
TD2 <- TOY[sample(1:length(TOY$x),n),]
r <- lm(y~0+x,TD2) #regressing y against
reg <- lm(y~x,TD2)
res <- reg$residuals
result[i]<- mean(TOY(TD2$x)%*%res)
 }

【问题讨论】:

  • 您希望TOY(TD2$x) 会发生什么?

标签: r for-loop simulation


【解决方案1】:

后面有 () 的都是函数,所以 TOY() 调用的是不存在的 TOY 函数。您需要使用方括号 []。此外,您采样的方式可能不起作用。在下面试试这个:

TOY = data.frame(x=rnorm(100),y=rnorm(100))
set.seed(123)
random.sims<-1000 
n<-50 
results<-c() #empty vector for results
TD2 <- c()
for (i in 1:random.sims) {
# since you sampled without replacement
TD2 <- sample(1:nrow(TOY))
reg <- lm(y~x,TOY[TD2,])
res <- reg$residuals
results[i]<- mean(TOY$x%*%res)
 }

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2021-03-04
    • 2012-10-29
    相关资源
    最近更新 更多