Writing a loop for randomly selecting rows of a matrix and doing a linear regression on data from rows and storing in a matrix

StackOverflow https://stackoverflow.com/questions/20390155

  •  29-08-2022
  •  | 
  •  

Вопрос

I need to write a program that does the following in R:

I have a data set (42 rows, 2 columns) of y variables and x variables.

I want to randomly select 12 rows from this matrix and record the coefficients (slope and intercept) of a linear regression of the randomly generated matrix. I would also like to write a loop for this so I can repeat this 1000 times, so I can then have a matrix with 1000 rows and 2 columns filled in with the slopes and intercepts of the 1000 randomly selected sets of 12 rows from my data set.

I am able to get this far but do not know how to incorporate a loop into the code, and a way to store the coefficients into a a matrix.

#Box.Z and Box.DC.gm are columns of data used to generate my initial matrix of data

A <- matrix(c(Box.Z, Box.DC.gm), nrow=42)
B <- A[sample(42, 12), ]
C <- lm(B[,2] ~ B[,1])
D <- matrix(c(coefficients(C)), ncol =2)
Это было полезно?

Решение

Something like this maybe:

#set.seed(23)
A <- matrix(runif(84),ncol=2)

randco <- function(A) {
  B <- A[sample(42,12),]
  lm(B[,2] ~ B[,1])$coefficients
}

t(replicate(10,randco(A)))

#      (Intercept)        B[, 1]
# [1,]   0.6018459 -0.1643174222
# [2,]   0.4411607  0.0005322798
#...
# [9,]   0.3201649  0.4848679516
#[10,]   0.5413830  0.1850853748
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top