I am trying to create a function that takes a sequence of x values and vector to be used in an equation. For each value in the vector dM, I would like to calculate probabilities of each x value occurring (equation in function for loop). Put all probabilities in a data.frame with associated dM values (so two columns) and then use ggplot to map the line to show each relationship.
For example: pred_prob(0,870,50,c(-100,0)) this would mean from 0 to 870 by 50, calculate the probabilities for each value in the vector. Here is my working code. I suspect the nested for loop is not working as intended or how the data being stored is not correct.
pred_probs <- function(from,to,by,dM){
pred_females = numeric(0)
dM <- as.vector(dM)
x_values <- seq(from = from, to = to, by = by)
for( j in dM){
for(i in x_values){
prob=exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)/(1 + exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j))
pred_females = c(pred_females,prob,j)
}
pred_females <- as.data.frame(pred_females)
ggplot(pred_females) +
geom_line(mapping = aes(x = x_values, y = pred_females,
group = j,
color = j))
}
}
pred_prob(0,870,50,c(-100,0))
EDIT:
Output graph should look like this (only tw:

EDIT (again): This function satisfies my needs:
pred_probs <- function(to, from, by, dep){
tibble() %>%
expand(j=dep, i=seq(to, from, by)) %>%
mutate(prob=exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j)/(1 + exp(-2.048e-02*i + 2.087e-02*j + -2.216e-05*i*j))) %>%
ggplot() +
geom_line(aes(x = i, y = prob, color = as.factor(j)))
}
pred_probs(0,870,50,c(-300,-200,-100,0,100))

