モデルのパラメータの調整をする時、色んなパラメータの値を試してはプロットを見たいときってあるじゃないですか。ggplot
を含んだ関数をfor
に渡してもいいけど、lapply
に渡したほうが(多分)早い&コードもすっきり。
以下は、サンプルデータに異なる次元のpolynomialでlinear modelをfit する例のコードです。
library(ggplot2)
# create simulation data
N <- 100 # number of observation
K <- 10 # number of covariates
X <- rnorm(n = N, mean = 0, sd = 1)
Y <- X**3 + rnorm(n = N, mean = 0, sd = 1)
data <- data.frame(Y = Y, X = X)
# function to plot predicted values of linear regression
# with i'th degree polynomial
plotPoly <- function(.i, .data){
# make sure to set the first argument as the variable to be iterated over
fit <- lm(Y ~ poly(X, degree = .i, raw = T), data = .data)
data$pred <- predict(fit)
ggplot(data) +
geom_point(aes(x = X, y = Y)) +
geom_line(aes(x = X, y = pred), color = 'red') +
ggtitle(paste('Degree = ', .i, sep = " "))
}
out <- lapply(X = 1:5, FUN = plotPoly, .data = data)
# see the plots
out[[1]]
out[[2]]
out[[3]]
out[[4]]
out[[5]]
関数の最初のargumentを変化させるパラメータにすることがみそ。