简体   繁体   中英

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". 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. It is saved in my working directory as an RDS file. 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. 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)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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