简体   繁体   English

运行模拟:for 循环中的随机抽样

[英]Running simulations: random sampling in a for loop

I'm trying to run this loop using a data set (TOY) of only x and y values (made up arbitrarily for this exercise) and I continue to receive this Line 7 error: Error in TOY(TD2$x): could not find function "TOY".我正在尝试使用只有 x 和 y 值(为本练习任意组成)的数据集 (TOY) 运行此循环,并且我继续收到第 7 行错误:TOY 中的错误(TD2$x):无法找到 function“玩具”。 I'm not sure how to fix the fact that R seems to be recognizing TOY as a function in that line, rather than as a data set.我不确定如何解决 R 似乎将 TOY 识别为该行中的 function 而不是数据集的事实。 It is saved in my working directory as an RDS file.它作为 RDS 文件保存在我的工作目录中。 Any help is greatly appreciated.任何帮助是极大的赞赏。

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

Anything with a () after is a function, so TOY() is calling the TOY function which doesn't exist.后面带有 () 的任何东西都是 function,所以 TOY() 正在调用不存在的 TOY function。 You need to use the square brackets [].您需要使用方括号 []。 Also the way you sampled might not work.此外,您采样的方式可能不起作用。 Try this below:在下面试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM