我試圖模擬兒童人口的兩個體重和年齡值。這些數據應該是S形相關的,以便在低齡時體重緩慢變化,然後在經過約30周後月經體重增加加速,其開始平穩過去約50周。R - 模擬乙型相關協變量
我已經能夠使用下面的代碼來獲得體重和年齡之間的線性相關性,以相當好地工作。我遇到麻煩的部分是調整此代碼以獲得更多的S形數據。任何建議將不勝感激。
# Load required packages
library(MASS)
library(ggplot2)
# Set the number of simulated data points
n <- 100
# Set the mean and standard deviations for
# the two variables
mean_age <- 50
sd_age <- 20
mean_wt <- 10
sd_wt <- 4
# Set the desired level of correlation
# between the two variables
cor_agewt <- 0.9
# Build the covariance matrix
covmat <- matrix(c(sd_age^2, cor_agewt * sd_age * sd_wt,
cor_agewt * sd_age * sd_wt, sd_wt^2),
nrow = 2, ncol = 2, byrow = TRUE)
# Simulate the correlated results
res <- mvrnorm(n, c(mean_age, mean_wt), covmat)
# Reorganize the simulate data into a data frame
df <- data.frame(age = res[,1],
wt = res[,2])
# Plot the results and fit a loess spline
# to the data
ggplot(df, aes(x = age, y = wt)) +
geom_point() +
stat_smooth(method = 'loess')
電流輸出:
理想輸出(雖然在較小的年齡範圍和權重):
優秀 - 這工作出色。你知道是否可以將模擬的重量值限制爲正值而不降低標準偏差? – Entropy 2014-11-02 22:41:57
不客氣。這是可能的,但這不是一個簡單的解決方法,並且使問題比首先說明的要困難得多。用截斷的正態替換正常的錯誤可能會讓你關閉,例如。 'sim_wt <-truncnorm :: rtruncnorm(N,0,...,平均值= M *重量,sdfit)'。但是,一個確切的解決方案更復雜,因爲您現在不僅需要指定平均值(wt)〜平均值(年齡)的函數形式,還要指定方差。 – 2014-11-03 12:25:56
感謝您提供豐富而貼心的回覆。 – Entropy 2014-11-03 16:29:48