Reputation: 13
I have a vector (in this case extracted from a data frame) that I would like to calculate a some sums from using a two additional vectors containing start and end indices of the data vector to be used. For this, I am working in R.
For example, my vector to use for calculations is:
Data Vector:
[1] 1.45
[2] 1.56
[3] 1.57
[4] 1.40
[5] 3.45
[6] 1.45
[7] 1.66
[8] 2.03
[9] 1.33
Using other information in my data frame, I have calculated two other vectors containing the index positions of the above vector which I have called "start" and "stop" to denote the ranges between which I want to sum values. For example:
Start:
[1] 1
[2] 4
[3] 7
End:
[1] 3
[2] 6
[3] 9
I would like to use these two index vectors to sum between elements 1-3, 4-6, and 7-9 in my data vector. I'm struggling with a way to implement this across a data frame with several hundred rows.
I'm now attempting to write a function to do this, but wanted to put this up in case there is a simpler solution that I am missing.
Upvotes: 1
Views: 1821
Reputation: 121
This will work without too many checks and does not cover N/As (hopefully you will have filtered them out from the data.frame the number vector came from).
subSums <- function(vector, start_vector, end_vector){
if (length(start_vector) != length(end_vector)){
print("Start and End Point vectors are not the same length")
return()
}
result <- NULL
for (index in seq_along(start_vector)) {
result[index] <- sum(vector[start_vector[index]:end_vector[index]])
}
return(result)
}
example of use:
vec<-1:20
subSums(vec, c(1,3), c(2,4))
Upvotes: 1
Reputation: 192
Maybe there is a better solution, but I wrote some quick code that does what you want for a single vector, could rewrite some of it to calculate sums for multiple columns I am sure, if that is what you want.
sum<-c(rep(0,length(start)))
for (i in 1:length(start)){
for (j in start[i]:end[i]){
if(is.na(data[j] == FALSE)){
sum[i]<-sum[i]+data[j]
}
}
}
Edited to work with NAs. Again probably a better way to do it (I'm not R expert either) but that should work.
Upvotes: 1