【发布时间】:2017-02-26 09:51:08
【问题描述】:
我是 R 的相对新手(STATA 难民)。
我有一个数据框,它的观察对象是个人。我还有一个按年龄划分的退休金余额模型。我想根据每个人的年龄(上次生日的年龄)将预测的退休金余额附加到每个人身上。 该模型旨在平滑按年龄划分的退休金余额分组平均数据:
library(mgcv)
# Age bracket mid-points
x = seq(22, 62, 5)
# Male age-bracket super balance medians
y = c(6, 21, 42, 65, 75, 110, 137, 150, 230)
# Model the super as a function of age bracket
mod = gam(y ~ s(x, k = 8), family = Gamma(link = "log"))
# Predict the super balance for each age
pred = cbind(Age = 20:64, Super = predict(mod, data.frame(x = 20:64), "response"))
# Plot raw data and predictions for each year
plot(y ~ x, xlim = c(20, 64), ylim = c(0, 250), las = 1)
points(pred, col = "red")
我还有另一个数据框age,它有很多向量,其中一个是age。我想做的是向这个数据框添加一个新向量,该向量使用 mod 根据他们的年龄来预测个人的退休金余额。 作为示例数据框(不是我的真实数据):
age=data.frame(seq(25,51,2))
另一种方法是使用数据框 pred 并从适当的年龄行中读取 super 的相关值并将其附加到 age。
不幸的是,我不知道如何做这两件事。我想一定有一种方法可以使用 vapply() 来运行模型随着年龄增长的预测,但无法让它发挥作用。 我也试过 cbind():
cbind(age,y = predict(mod, newdata = age))
但收到错误消息,告诉我行数不匹配。 非常感谢任何帮助。
【问题讨论】:
标签: r