0

I am trying to fit a for Loop in R in order to run correlations for multiple subsets in a data frame and then store the results in a vector.

What I have in this loop is a data frame with 2 columns, x and y, and 30 rows of different continuous measurement values in each column. The process should be repeated 100 times. The data can be invented. What I need, is to compute the Spearman's rho for the first five rows (between x and y) and then for increasing subsets (e.g., the sixth first rows, the sevenths first rows etc.). Then, I'd need to store the rho results in a vector that I can further use.

What I had in mind (but does not work):

sortvector <- 1:(30) 
for (i in 1:100) 
{
sortvector <- sample(sortvector, replace = F) 
xtemp <- x[sortvector] 
rho <- cor.test(xtemp,y, method="spearman")$estimate  
}

The problem is that the code gives me one value of rho for the whole dataframe, but I need it for increments of subsets. How can I get rho for subsets of increasing values in a for-loop? And how can i store the coefficients in a vector that i can use afterwards?

Any help would be much appreciated, thanks.

Cheers

YMCA
  • 11
  • 1
  • We should all vote for closing this question since it does not have the dataset, and tried code. – Sal-laS Sep 08 '18 at 13:26
  • What Salman is trying to say: Welcome to StackOverflow. Please read [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and give us something to work with, i.e. data, the code you have tried and expected output. – markus Sep 08 '18 at 13:28

1 Answers1

0

The easiest approach is to convertfor loop into sapply function, which returns a vector of rho's as a result of your bootstrapping:

sortvector <- 1:(30)
x <- rnorm(30)
y <- rnorm(30)

rho <- sapply(1:100, function(i) {
  sortvector <- sample(sortvector, replace = F) 
  xtemp <- x[sortvector] 
  cor.test(xtemp, y, method = "spearman")$estimate  
})

head(rho)

Output:

         rho          rho          rho          rho          rho          rho 
 0.014460512 -0.239599555  0.003337041 -0.126585095  0.007341491  0.264516129 
Artem
  • 3,304
  • 3
  • 18
  • 41