請撰寫一個函數 checkNormality()
用來檢視輸入的 vector (x
) 趨近常態分配的程度。checkNormality()
達成此目的的方式是將傳入的資料繪製成直方圖,再於直方圖之上疊加常態分配的機率密度函數曲線。
要求:
x
長度自動調整長條的數量 (可透過 geom_histogram()
的參數 bins
進行設置。請自行實驗找出適合的方式去自動調整 bins
的數量,讓繪製出來的直方圖盡量平滑沒有斷裂1)geom_point()
繪製常態分配機率密度之曲線。常態分配的參數依據傳入的 x
之平均與標準差決定。library(ggplot2)
<- function(x) {
checkNormality #### Finish this function (you can use the template below) ####
<- length(x) # 自動依據 x 計算長條數量
bins
<- ggplot() +
plt geom_histogram(bins = bins) + # 實際資料之直方圖
geom_point() # 常態分配曲線
return(plt)
}
###### Do not modify the code below ########
set.seed(1914)
<- rnorm(200)
d checkNormality(d)
<- rnorm(1000)
d checkNormality(d)
<- runif(1000)
d checkNormality(d)
Should print out something like:
請根據上圖的因果結構 (箭號代表因果關係) 模擬出 G, P, C 這三個變項的資料,並將結果儲存成一個 data frame df1
:
set.seed(1)
###### Do not modify the code above #######
# Write your code here
###### Do not modify the code below ######
head(df1)
#> Error in head(df1): object 'df1' not found
# Should print out:
#> G P C
#> 1 -0.6264538 -0.5491507 -0.04063941
#> 2 0.1836433 -0.1132253 1.18234985
#> 3 -0.8356286 -2.0188709 -3.72527710
#> 4 1.5952808 1.6065735 3.41258588
#> 5 0.3295078 1.3211088 1.72001223
#> 6 -0.8204684 0.7734991 -1.70961817
請使用上一題的 df1
繪製出此圖:
# Write your code here
上方的因果結構中,G, P, U, C 可以被歸類成三種因子:混淆因子 (Confounder)、對撞因子 (Collider) 與中介因子 (Mediator)
請將 G, P, U, C 這四個因子進行分類 (請在正確的類別填入 G, P, U, C):
請根據上圖的因果結構模擬出 G, P, U, C 這四個變項的資料,並將結果儲存成一個 data frame df2
:
2
1
0.5
2
1
set.seed(1)
###### Do not modify the code above #######
# Write your code here
###### Do not modify the code below ######
head(df2)
#> Error in head(df2): object 'df2' not found
# Should print out:
#> G P U C
#> 1 -0.6264538 -0.04063941 0.07730312 0.5328409
#> 2 0.1836433 1.18234985 -0.29686864 1.2343397
#> 3 -0.8356286 -3.72527710 -1.18324224 -8.1580295
#> 4 1.5952808 3.41258588 0.01129269 6.6930951
#> 5 0.3295078 1.72001223 0.99160104 5.1353315
#> 6 -0.8204684 -1.70961817 1.59396745 -2.4174775
假定 vector x
是來自連續型機率分配如常態分配、均等分配等。↩︎