【发布时间】:2021-04-19 06:10:41
【问题描述】:
我正在尝试创建一个函数,该函数采用一系列 x 值和向量以用于方程。对于向量dM 中的每个值,我想计算每个 x 值出现的概率(循环函数中的方程)。将所有概率与关联的 dM 值(所以两列)放在 data.frame 中,然后使用 ggplot 映射线以显示每个关系。
例如:pred_prob(0,870,50,c(-100,0)) 这意味着从 0 到 870 x 50,计算向量中每个值的概率。这是我的工作代码。我怀疑嵌套的 for 循环没有按预期工作,或者存储的数据不正确。
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))
编辑:
编辑(再次): 这个功能满足我的需求:
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))
【问题讨论】: