1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

パラメータをループしてggplotしたい

Last updated at Posted at 2019-07-08

モデルのパラメータの調整をする時、色んなパラメータの値を試してはプロットを見たいときってあるじゃないですか。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を変化させるパラメータにすることがみそ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?