Camellia Hilker
Camellia Hilker

Reputation: 58

Concatenating large vector variables

I'm trying to compile my variables (vectors) s1, s2, and sn from the for loop below. The loop creates 19 matrices of 1000 columns and various rows (created by the loop) of random numbers. Those values ("samps") are then calculated with the functions calc_sds_1, calc_sds_2, and calc_sds_n (takes the standard deviation (n, n-1, n-2) of each column of the matrix).

Basically I want the variables s1, s2, sn to collect those calculated values from each iteration of the loop and return the full vector (should be 19000 values) to the global environment.

calc_sds_1 <- function(x){
  sds_1 <- vector("numeric", 1000)
  for (i in 1:1000){
    sds_1[i] = std_1(x[,i])
  }
sds_1
}

calc_sds_2 <- function(x){
  sds_2 <- vector("numeric", 1000)
  for (i in 1:1000){
    sds_2[i] = std_2(x[,i])
  }
sds_2
}

calc_sds_n <- function(x){
  sds_n <- vector("numeric", 1000)
  for (i in 1:1000){
    sds_n[i] = std_n(x[,i])
  }
sds_n
}

s1 <- numeric()
s2 <- numeric()
sn <- numeric()

for (i in 2:20) {
    samps <- replicate(1000, rnorm(i))
    calc_sds_1(samps)
    calc_sds_2(samps)
    calc_sds_n(samps)
    s1 <- s1 + sds_1
    s2 <- s2 + sds_2
    sn <- sn + sds_n
    return(s1)
    return(s2)
    return(sn)
}

Upvotes: 0

Views: 54

Answers (1)

vaettchen
vaettchen

Reputation: 7659

Your function can only return one result. Pack your three vectors into one list and return the list:

calc_sds_1 <- function( x ){
    # your code
    return( list( s1, s2, sn ) )
}

Get the list into the global environment by

x_back <- calc_sds_1( x )

and then you can access your vectors as x_back[[ 1 ]] etc.

If you want / need the vector names, you need to re-assign, eg.

s1  <- x_back[[ 1 ]]
s2  <- x_back[[ 2 ]]
sn  <- x_back[[ 3 ]]

although for me it works better to keep them in the list and rather work with the list.

Upvotes: 1

Related Questions