Edit: It had cut the top line of code, sorry.
I'm trying to make a very simple loop for an array. For each time period, I want it to take the amount for g in the last period and double it. The error I get is that it doesn't like the dimensions. But i've tried a number of things, nothing I've tried works.
Edit: So g in period1 should be 20, in period2 it should be 40, in period3 80, in period4 160.
g=20
d=10
t=0.1*d
c=t
#Number of periods
nPeriods = 4
#central vector
B = c(g,t,c,d)
#central array
column.names = c('aaaaaaa', 'bbbbbb')
row.names = c('ggggg', 'hhhhh')
matrix.names = c(1:nPeriods)
C = array(c(B), dim=c(2, 2, nPeriods),
dimnames = list(row.names, column.names, matrix.names))
print(C)
#make a slice to view as data table
G = C[,,1]
for (i in 2:nPeriods){
g[,,i]=g[,,i-1]*2
}
H = C[,,3]
CodePudding user response:
If you remove the requirement for g, with a few things updated, this code works. I don't know what output you were expecting, though. I added the output here, along with the code. If something isn't what you were expecting, let me know by updating your question and leaving a comment so that I know that you did (SO sends a message with a comment).
d=10
t=0.1*d
c=t
#Number of periods
# nPeriods = 4 <- commented out, used 3
nPeriods = 3
#central vector
# B = c(g,t,c,d) <- commented out, used t, c, and d
B = c(t, c, d)
# [1] 1 1 10
Without g
here, you get a 3 dimensional array, which from your question seems like what you wanted.
#central array
column.names = c('aaaaaaa', 'bbbbbb')
row.names = c('ggggg', 'hhhhh')
matrix.names = c(1:nPeriods)
C = array(c(B), dim=c(2, 2, nPeriods),
dimnames = list(row.names, column.names, matrix.names))
print(C)
# , , 1
#
# aaaaaaa bbbbbb
# ggggg 1 10
# hhhhh 1 1
#
# , , 2
#
# aaaaaaa bbbbbb
# ggggg 1 1
# hhhhh 10 1
#
# , , 3
#
# aaaaaaa bbbbbb
# ggggg 10 1
# hhhhh 1 10
#
#make a slice to view as data table
G = C[,,1]
# aaaaaaa bbbbbb
# ggggg 1 10
# hhhhh 1 1
Since there was no g
and it would not have been the right dimensions if it were used in B
, I changed this to the only object with the right dimensions: C
.
for (i in 2:nPeriods){
C[,,i]=C[,,i-1]*2 # instead of g... C
}
C
# , , 1
#
# aaaaaaa bbbbbb
# ggggg 1 10
# hhhhh 1 1
#
# , , 2
#
# aaaaaaa bbbbbb
# ggggg 2 20
# hhhhh 2 2
#
# , , 3
#
# aaaaaaa bbbbbb
# ggggg 4 40
# hhhhh 4 4
#
H = C[,,3]
# aaaaaaa bbbbbb
# ggggg 4 40
# hhhhh 4 4
CodePudding user response:
I think you need to change this:
for (i in 2:nPeriods){
g[,,i]=g[,,i-1]*2
}
to this:
for (i in 2:nPeriods){
C[,,i]=C[,,i-1]*2
}