chenchenmomo
chenchenmomo

Reputation: 233

How to use for loop to split matrix or data frame using R?

I want use for loop function to output n/2 NewMatrix, NewMatrix <- OldMatrix[,c(i,i+1)] , i= ncol(OldMatrix).

And give them names as the format: NewMatrix_i, in order to I can access individual matrix easily.

OldMatrix
          A   B   C   D   E   F   G   H   I   J   K  
    [1,] "1" "1" "C" "F" "F" "B" "F" "F" "1" "1" "4"
    [2,] "1" "1" "C" "F" "F" "B" "F" "F" "1" "1" "4"
    [3,] "1" "1" "C" "F" "F" "B" "F" "F" "1" "1" "4"
    [4,] "5" "5" "C" "F" "F" "B" "F" "F" "1" "1" "4"
    [5,] "5" "5" "C" "F" "F" "B" "F" "F" "1" "1" "4"
    [6,] "5" "5" "C" "F" "F" "B" "F" "F" "1" "1" "4"

Upvotes: 0

Views: 225

Answers (1)

akrun
akrun

Reputation: 886998

May be this helps:

 indx <- 1:(ncol(OldMatrix)-1) 
 lst1 <- setNames(lapply(indx, function(i) OldMatrix[,c(i, i+1)]), paste("NewMatrix",indx, sep="_"))

 lst1$NewMatrix_10
 #      J   K  
 #[1,] "1" "4"
 #[2,] "1" "4"
 #[3,] "1" "4"
 #[4,] "1" "4"
 #[5,] "1" "4"
 #[6,] "1" "4"

Upvotes: 1

Related Questions