Reputation: 157
I have a 2D array A with 10,000 rows and 2 columns.
At a first instance I want to use only the first 200 rows of the array A. I did the following: New_array=A[A(1:200) ,]
Each time I want to increase the number of the rows by 50. i.e. in the second iteration I want to have access on the 250 rows of matrix A, third iteration 300 and so on until I reach the original size of the matrix.
I know that I have to create a for loop but I struggle. Any help will be highly appreciated
Upvotes: 0
Views: 1687
Reputation: 1433
The seq
function allows you to specify intervals in a sequence, as shown in @d.b's comment.
seq(0, 20, by = 5)
[1] 0 5 10 15 20
The output of seq
can then be used to drive the loop. Here i
is used as the endpoint for a sequence in each iteration.
for ( i in seq(5, 20, by = 5) ) {
print(1:i)
}
[1] 1 2 3 4 5
[1] 1 2 3 4 5 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Applied to your example, the sequences can be used to subset the matrix
# Example matrix
m <- 10000
n <- 2
A <- matrix(1:(m*n), ncol = n)
head(A)
[,1] [,2]
[1,] 1 10001
[2,] 2 10002
[3,] 3 10003
[4,] 4 10004
[5,] 5 10005
[6,] 6 10006
# Iterate with a loop
jump <- 5 # I'm using 5 instead of 50
for ( i in seq(jump, m, by = jump) ) {
print(paste("i =", i))
print( A[1:i, ] ) # subset the matrix
if ( i > 15 ) break # limiting the output for readability
}
[1] "i = 5"
[,1] [,2]
[1,] 1 10001
[2,] 2 10002
[3,] 3 10003
[4,] 4 10004
[5,] 5 10005
[1] "i = 10"
[,1] [,2]
[1,] 1 10001
[2,] 2 10002
[3,] 3 10003
[4,] 4 10004
[5,] 5 10005
[6,] 6 10006
[7,] 7 10007
[8,] 8 10008
[9,] 9 10009
[10,] 10 10010
[1] "i = 15"
[,1] [,2]
[1,] 1 10001
[2,] 2 10002
[3,] 3 10003
[4,] 4 10004
[5,] 5 10005
[6,] 6 10006
[7,] 7 10007
[8,] 8 10008
[9,] 9 10009
[10,] 10 10010
[11,] 11 10011
[12,] 12 10012
[13,] 13 10013
[14,] 14 10014
[15,] 15 10015
[1] "i = 20"
[,1] [,2]
[1,] 1 10001
[2,] 2 10002
[3,] 3 10003
[4,] 4 10004
[5,] 5 10005
[6,] 6 10006
[7,] 7 10007
[8,] 8 10008
[9,] 9 10009
[10,] 10 10010
[11,] 11 10011
[12,] 12 10012
[13,] 13 10013
[14,] 14 10014
[15,] 15 10015
[16,] 16 10016
[17,] 17 10017
[18,] 18 10018
[19,] 19 10019
[20,] 20 10020
Upvotes: 1