I am new to loops and I'm struggling to format my outputs. I am trying to modify a time series of species abundance at various time points (i), by various magnitudes (j) for multiple species (k). For each of these options I want a column which shows abundance over time.
I have written a loop that works when I manually input various values of i,j and k (i.e. I get single column that has the correct values), but I can't figure out how to correctly index the output matrix.
A dummy data set looks like this (where x and y are different species and sample number is time):
dat<- data.frame(x = sample(1:100, 100, replace = TRUE), y = sample(1:100, 100, replace = TRUE))
For my loop I also create some other objects:
length <- nrow(dat)
change <- as.matrix(seq(0.0,0.99,0.2))
change.length <- nrow(change)
and a final matrix to populate (which has the correct dimensions). The -40 is there because I'm not modifying the first 20 or the last 20 abundances in the time series
final_matrix <- array(0,c(length,(((length-40)*change.length)*2))) # 2 is the number of species in this example
The loop looks like this:
for(i in 1:(length-40)) {
for(j in 1:change.length){
for(k in 1:2){
timestep1 <- dat[0:(19+(i)),k] # selecting rows that will not be modified based on min + i for a given species k
timestep2 <- dat[(20+i):(length),k] # selecting rows that will be modified for any given species k (columns)
result1 <- timestep1*1 # not making any changes to the abundance data
result2 <- timestep2*change[j,1] # multiplying abundance by change (j)
resultloop<-c(result1,result2) # binding the two matrices into a single column with 100 rows
final_matrix[,i*j*k] <- resultloop
}}}
The final matrix indexed as it is, produces the incorrect number of columns with weird results such as columns with all zeros.
How can I index this matrix so that each column (with 100 rows representing abundances over time) is indexed for each value of i,j and k?
EDIT: An example (simulated) dummy data set to illustrate what I would like the output to look like:
dat<- data.frame(Spx_I1_j1 = sample(1:100, 100, replace = TRUE),
Spx_I2_j1 = sample(1:100, 100, replace = TRUE),
Spx_I3_j1 = sample(1:100, 100, replace = TRUE),
# etc...
Spx_I1_k2 = sample(1:100, 100, replace = TRUE),
Spx_I2_k2 = sample(1:100, 100, replace = TRUE),
#etc...
Spy_I1_k1 = sample(1:100, 100, replace = TRUE),
Spy_I2_k1 = sample(1:100, 100, replace = TRUE))
Where each column of a 100 abundance values is represented by individual columns for each modified time step sequence (i) for each magnitude change (j) for each species (k).
Many thanks in advance for any help or advice you may have on this matter.