mccinthenyc
mccinthenyc

Reputation: 61

R - how to "insert" a value into a row for a fill-in matrix

EDIT

Hello, here's a more reproducible example.

I have an R script that borrows heavily from this blogpost and I'm trying to make some modifications to how the matrix of each simulation is constructed.

I'm really bad with for-loops in R, so I need a little help figuring it out.

What I'm hoping to do is find a way to inject a value to (re-baseline) for a certain row (or rows) ... maybe I'm over thinking this and missing something obvious?

# starting cash for each "simulation"
principle = 100

#starting inflation assumption
inflation = .05

#starting returns
returns = .02

# number of time units (lets say months)
n.obs = 5

# number of simulations (columns)
n.sim = 5

# time I retire and get access to 401k
  t_retire = 4
    
# amount of money available to be added to my principal at t==t_retire
  retire = 100

# simulate cases - they're all the same in this example
nav = matrix(start.capital, n.obs + 1, n.sim)
for (j in 1:n.obs) {
  nav[j + 1, ] = (nav[j, ] * (1 + returns - inflation))
}

I want to edit this for-loop to add the "retire" value to my existing "principle" at row (t_retire) = 4.

Upvotes: 0

Views: 153

Answers (1)

IRTFM
IRTFM

Reputation: 263411

With the minimal example I think this might be what is desired:

 nav = matrix(start.capital, n.obs + 1, n.sim)

 for (j in 1:n.obs) { if(j==t_retire){nav[j, ] <- nav[j-1, ] + retire}
    nav[j + 1, ] = (nav[j, ] * (1 + returns - inflation))
 }
 nav
 #----------------------
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 100000.00 100000.00 100000.00 100000.00 100000.00
[2,]  97000.00  97000.00  97000.00  97000.00  97000.00
[3,]  94090.00  94090.00  94090.00  94090.00  94090.00
[4,]  94190.00  94190.00  94190.00  94190.00  94190.00
[5,]  91364.30  91364.30  91364.30  91364.30  91364.30
[6,]  88623.37  88623.37  88623.37  88623.37  88623.37

If it's not the desired modification then at least it may form the basis for clarification. Not that the R habit of filling rows with copies of single values is at work here.

Upvotes: 1

Related Questions