user4670961
user4670961

Reputation: 137

creating a list of matrices in R

Using a for loop, I have generated a list of matrices that are labeled X_1, X_2, X_3, ... etc.

I am now trying to run a series of functions on each matrix and I wrote another for loop:

for (i in matrices) {
            df <- count(i)
            df$count <- df$freq
            df$freq <- df$count/nrow(i)  #freq = pi in H1 equation
            for (j in names){
            assign(paste("hap",j,sep="."), df)      
            }
        }

I tried to generate the list of matrices using a sequence script:

matrices <- (paste("X",seq(1,nrow(windows)), sep="_"))

which results in the output: "X_1" "X_2" "X_3" "X_4" "X_5" Although this is a list, it is just a list of characters and does not actually reference the matrices. It seems to work if I manually type in the list of matrix names:

matrices <- list(X_1, X_2, X_3, X_4, X_5, ...)

but I was hoping to automate this so I can apply the script to large datasets. If I try combining these with

matrices <- list(paste("X",seq(1,nrow(windows)), sep="_"))

I get the same thing as the first script: "X_1" "X_2" "X_3" "X_4" "X_5"

Is there a way to generate sequential lists of matrices so they can be used in a for loop?

I have also tried lapply, but I am less comfortable with this than loops and I could not get the functions I wanted to do to work in lapply.

Upvotes: 0

Views: 463

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522636

I would go about this by adding each matrix to a list at the time you actually create each matrix, e.g.

lst <- list(X_1, X_2, ..., X_N)

Then, when you want to apply a function to each matrix you can simply use lapply, e.g.

result <- lapply(lst, function(x) fun(x))

where fun() takes a matrix as input and does something with it.

Upvotes: 1

Related Questions