I've never used the lapply and sapply functions in R before and I have heard that they are preferred to for loops..
Here's my code:
for (i in seq(length(variable_a)))
{
for (j in seq(length(variable_b)))
{
variable_c[i,j] = variable_c[i,j] + variable_b[j] * variable_d[i]
variable_e[i,j] = variable_e[i,j] + variable_c[i,j] * variable_a[i]
}
variable_f[1,i] = sum(variable_c[i,])
variable_f[2,i] = sum(variable_e[i,])
}
How do I use the apply family of functions to implement these loops? I've looked at all sorts of examples but I must be missing a concept somewhere.
Update:
There are a lot of things that happens before this nested loop, as this code is part of a simulation (not of a real world problem, more for a hobby), but I'll try to give some sample data.
All of the elements in all of the variables are numbers. variable_a is not very long, containing less than 10 elements. It's numbers can be anything greater than 0.
variable_b are also numbers greater than 0, and is made by combining several smaller variables of the same type. These smaller variables are made using different parameters and many calculations, so variable_b cannot be made in one fell swoop.
variable_d are numbers between 0 and 1. It is calculated as follows:
variable_d = variable_a
sum_d = sum(variable_d)
for (i in seq(length(variable_d)))
{
variable_d[i] = sum_d / variable_d[i]
}
sum_d = sum(variable_d)
for (i in seq(length(variable_d)))
{
variable_d[i] = variable_d[i] / sum_d
}
In effect, the higher any given element in variable_a is, the lower the corresponding element in variable_d will be.
variable_f is what is returned to another function
variable_c and variable_e are initialized as arrays as follows
variable_c = array(0, dim = c(length(variable_a), some_other_variable_created_earlier_here)
Normally, the some_other_variable_created_earlier_here is an integer of in the millions, so I will provide a much abbreviated list here.
variable_a[1] = 37.2
variable_b = 0 0 0 0 0 0 0 0 0 0 1 0 2
variable_d = 1 (if variable_a[1] = 30 and variable_a[2] = 90, then variable_d = 0.75 0.25)
variables_c and e are arrays
I hope this helps.