Reputation: 405
Given two vectors x,y:
x <- c( 1.0, 2.0, 3.0, 4.01, 5.12, 9.59)
y <- c( 0.1, 0.2, 0.3, 0.78, 0.45, 6.78)
In R notation using vector operation (not for loop), how to take y divided by the sum of some subset of x where I specify the indices:
y / ( x[1] + x[2] + x[3] + x[4] )
This would be the same as manually taking y / 10.01 and returning a vector length y. I've tried using seq() and subsetting but don't know.
Upvotes: 1
Views: 82
Reputation: 61154
Maybe using sum
and head
functions:
> y/sum(head(x, 4))
[1] 0.00999001 0.01998002 0.02997003 0.07792208 0.04495504 0.67732268
you can also use seq
y/sum(x[seq(4)])
which is the same as @Rcoster's comment y / sum(x[1:4])
Upvotes: 3