【发布时间】:2021-01-14 21:48:55
【问题描述】:
我正在尝试在嵌套列表中生成数据框中的所有行组合,在每个集合上拟合和预测线性模型,然后选择最佳集合(最小误差)。
我的数据框:
myFunction <- function (x) {
(x[2] - 5.1/(4 * pi^2) * (x[1] ^2) + 5/pi * x[1] - 6)^2 +
10 * (1 - 1/(8 * pi)) * cos(x[1] ) + 10
}
set.seed(1)
x1 <- runif(5)*15-5
x2 <- runif(5)*15
y <- as.matrix(apply(cbind(x1,x2),1,myFunction))
df <- data.frame(x1,x2,y)
我生成所有行的组合:
Mycomb <- function(elements, simplify = FALSE){
result <- lapply(seq_along(elements), function(m)
combn(elements, m, simplify = simplify))
result
}
combinations <- Mycomb(1:5)
sub_df_list <- lapply(combinations, function(inx_list)
lapply(inx_list, function(i) df[c(1, i),])
)
>sub_df_list
#[[1]]
#[[1]][[1]]
# x1 x2 y
#1 -1.0173701 13.47585 47.79895
#2 0.5818585 14.17013 99.96885
#[[1]][[2]]
# x1 x2 y
#1 -1.01737 13.475845 47.79895
#3 3.59280 9.911967 64.76098
#[[1]][[3]]
# x1 x2 y
#1 -1.017370 13.475845 47.79895
#4 8.623117 9.436711 60.39821
#[[1]][[4]]
# x1 x2 y
#1 -1.017370 13.4758453 47.79895
#5 -1.974771 0.9267941 82.26291
#[[2]]
#[[2]][[1]]
# x1 x2 y
#1 -1.0173701 13.475845 47.79895
#2 0.5818585 14.170129 99.96885
#3 3.5928005 9.911967 64.76098
#...
但我不知道如何在每个生成的集合上应用 fit 和预测 lm 以选择哪个集合产生的误差最小:
fit <- lm(y~x1+x2, sub_df_list)
mytest <- data.frame(x1=1,x2=2) # test data is fixed
pred <- predict(fit,mytest)
real <- myFunction(c(1,2))
sqrt((pred - real)^2) # calculates error
我真的不知道该怎么做。任何帮助将不胜感激。
【问题讨论】:
-
sub_df_list的结构重要吗? -
@LMc
sub_df_list的结构并不重要。
标签: r list loops combinations lapply