I ran into a problem in R where I need to manipulate a vector in R.
Lets say I have a vector of length 12:
vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
I now need to add the elements 1 2
, 3 4
, 5 6
etc. into a new vector, in the example that would be:
newvector <- c(3, 7, 11, 15, 19, 23)
I need to do the same for longer sequences, such that it adds the first three, then 4-6
, then 7-9
etc.
newvector <- c(6, 15, 24, 33)
and so on.
CodePudding user response:
One option could be:
tapply(x, cumsum(seq_along(x) %% 2 == 1), sum)
1 2 3 4 5 6
3 7 11 15 19 23
for n = 3:
tapply(x, cumsum(seq_along(x) %% 3 == 1), sum)
1 2 3 4
6 15 24 33
CodePudding user response:
Put the vector in a matrix and then use colSums
. Here's a function to do that.
vector <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
calculate_sum <- function(v, n) {
colSums(matrix(v, nrow = n))
}
calculate_sum(vector, 2)
#[1] 3 7 11 15 19 23
calculate_sum(vector, 3)
#[1] 6 15 24 33
CodePudding user response:
I would do this: split
splits the vector into n groups, and Reduce
sums the n-th elements of each group.
newvector <- Reduce(` `, split(vector,c(1,2)))
[1] 3 7 11 15 19 23
As a function, you could have this:
splitSum <- function(vector,groups) Reduce(` `, split(vector,c(1:groups)))
splitSum(vector,3)
[1] 6 15 24 33
CodePudding user response:
v <- 1:12
v1 <- rep(0, ((length(v))/2))
for(i in 1:((length(v))/2))
v1[i] <- v[i] v[i 1]
v1
I simply used a for
loop. Perhaps checking if the vector length can be split into groups of 2 and 3 elements before with an if
conditional may improve this...