0
votes

I want to sum a normalized vector separately in two direction in R.

For example, for a vector 3,4,5,6,10,9,8,7 after normalization 0.3, 0.4, 0.5, 0.6, 1.0, 0.9, 0.8, 07. I want to sum values < 1 on the left and right separately and find their difference. In this case, it will be left=0.3+0.4+0.5+0.6=1.8, right=0.9+0.8+0.7=2.4. The difference will be right minus left equals 0.6.

Below are some of my thoughts:

a <- c(3,4,5,6,10,9,8,7)
norm <- a/max(a)  # normalization
left <- sum(a[1:which.max(a)-1]) # left sum
right <- sum(a[which.max(a)+1:length(a)])  # right sum
diff <- right-left

Any suggestions for improvement?

1
Perhaps Reduce('-', tapply(norm, cumsum(c(TRUE, (a== max(a))[-1])), FUN = sum))akrun
I get 1.8 by summing 0.3 + 0.4 + 0.5 + 0.6# [1] 1.8akrun
good find for my math error. Haha.Jian

1 Answers

0
votes

We can use rleid to get the grouping variable, get the sum of the 'norm' for each group ('ind') and get the difference

library(data.table)
ind <- rleid(norm<1)
diff(as.numeric(tapply(norm[ind!=2], ind[ind!=2], FUN = sum)))
#[1] 0.6