squirrat
squirrat

Reputation: 405

iteration through vectors without using for loop

Given:

# Numeric Vector x and Vector y

x <- c( 0.00000,  62.10692, 119.75891, 169.28721, 216.71908, 239.77987, 264.28197)
y <- c( 0.0000000000, 0.0003332223, 0.0006662225, 0.0009990010, 0.0015044000, 0.0019960080, 0.0029910269)

How can i create a new vector using iteration through them without using a for loop? Here is what it looks like manually:

# Desired outcome 
c( y[2], sum( x[1:2] ), y[2] / sum( x[1:2] ) )
c( y[3], sum( x[1:3] ), y[3] / sum( x[1:3] ) )
c( y[4], sum( x[1:4] ), y[4] / sum( x[1:4] ) )
c( y[5], sum( x[1:5] ), y[5] / sum( x[1:5] ) )
c( y[6], sum( x[1:6] ), y[6] / sum( x[1:6] ) )
c( y[7], sum( x[1:7] ), y[7] / sum( x[1:7] ) )

Here using a for loop works, but is there a way to do this using subsetting or another R function? I'd rather use built in data types to handle numerics rather than string concatenation.

for (i in 2:7) cat( c( y[i], sum( x[1:i] ), y[i] / sum( x[1:i] ) ), ", ")

Upvotes: 0

Views: 1177

Answers (1)

CHP
CHP

Reputation: 17189

You can just do

cbind(y[-1], cumsum(x)[-1], y[-1]/cumsum(x)[-1])
##              [,1]       [,2]         [,3]
## [1,] 0.0003332223   62.10692 5.365301e-06
## [2,] 0.0006662225  181.86583 3.663264e-06
## [3,] 0.0009990010  351.15304 2.844916e-06
## [4,] 0.0015044000  567.87212 2.649188e-06
## [5,] 0.0019960080  807.65199 2.471371e-06
## [6,] 0.0029910269 1071.93396 2.790309e-06

y[-1] : all elements of y except first one
cumsum(x) : cumulative sum of x
cumsum(x)[-1] : all elements except first
cbind : join them as columns of data.frame

Upvotes: 4

Related Questions