Reputation: 1
I have a matrix in R, that looks like the following:
[,1] [,2] [,3] [,4]
[1,] 0 1 1 1
[2,] 2 12 22 32
[3,] 3 13 23 33
[4,] 4 14 24 34
[5,] 5 15 25 35
[6,] 6 16 26 36
[7,] 7 17 27 37
[8,] 8 18 28 38
[9,] 9 19 29 39
[10,] 10 20 30 40
I want to add every two rows are together, so that [1,] and [2,], create a new vector (say A). I need to do this repeatedly (so then [3,] and [4,] etc). I need to do this in a loop or some other way if that is possible (my actual data has 49 columns and 1000 rows). If possible, I would like it to create a new matrix with all the new data in, so from my original data I would have 500 rows, or here 5 rows?
I have tried the following code:
dips = matrix()
X <- seq(1, by = 2, len = 1000)
for(i in X)
{
dips[i] = population[i,] + population[i+1,]
}
I keep getting a warning, "number of items to replace is not a multiple of replacement length". And the data produced doesn't contain all 49 columns.
Sorry if this is a basic question or has already been solved, I am a beginner. Thank you in advance!
Upvotes: 0
Views: 1286
Reputation: 518
In the future, make sure to provide a minimal reproducible example of your data to make it easier for us to follow! You can show how you created dummy data (see my example below) or use something like dput()
to produce a text version of the data.
There are few things that I notice:
matrix(nrow = 500, ncol = 49)
X
has length of 1000, so it will try to find rows that are higher than the largest row index in population
. Take a look at tail(X)
and you will see that it goes up to 1999.Here is a small example with some dummy data that I made. The notable changes compared to your example are that I:
population
and half as many rows)nrow(population)
1:length(X)
instead of 1:X
in my for loopExample:
population <- matrix(1:400, byrow = F, ncol = 4)
sum <- matrix(nrow = nrow(population)/2, ncol = 4)
X <- seq(1, by = 2, len = nrow(population)/2)
for (i in 1:length(X)){
sum[i,] <- population[ X[i] ] + population[ X[i]+1 ]
}
Upvotes: 0
Reputation: 20473
This is probably a duplicate, but I couldn't locate a great match quickly, so here goes...you can use rowsum
:
my_matrix <- structure(c(0L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 12L,
13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 1L, 22L, 23L, 24L, 25L,
26L, 27L, 28L, 29L, 30L, 1L, 32L, 33L, 34L, 35L, 36L, 37L, 38L,
39L, 40L), .Dim = c(10L, 4L), .Dimnames = list(NULL, NULL))
rowsum(my_matrix, as.integer(gl(nrow(my_matrix), 2, nrow(my_matrix))))
# [,1] [,2] [,3] [,4]
# 1 2 13 23 33
# 2 7 27 47 67
# 3 11 31 51 71
# 4 15 35 55 75
# 5 19 39 59 79
Upvotes: 4