我正在尝试制作一个脚本来使用 R 生成一组具有人口统计信息的随机人。我希望它按行而不是按列生成,以便函数可以基于同一行中前一个函数的结果。我知道这可以通过 for 循环来完成(如下所示),但 for 循环在 R 中非常慢。我读过您可以使用apply或while更有效地执行循环,但我还没有弄清楚如何尽管许多尝试都失败了。下面是带有循环的功能代码示例。我将如何使用apply或while来做到这一点?
y <- 1980 ## MedianYr
d <- 0.1 ## Rate of NA responses
AgeFn <- function(y){
Year <- 1900 + as.POSIXlt(Sys.Date())$year
RNormYr <- as.integer((rnorm(1)*10+y))
Age <- Year - RNormYr
}
EduByAge <- function (Age, d) {
ifelse(Age < 17, sample(c("Some High School",NA), size=1,prob=c((1-d),d)),
ifelse(Age > 16 & Age < 19, sample(c("Some High School", "High School Grad",NA), size=1, prob=c(0.085, 0.604,d)),
ifelse(Age > 18 & Age < 21, sample(c("Some High School", "High School Grad", "Associates",NA), size=1,prob=c(0.085, 0.25, 0.354,d)),
ifelse(20 > Age & Age < 23, sample(c("Some High School", "High School Grad", "Associates", "Bachelors",NA), size=1,prob=c(0.085, 0.25, 0.075, 0.279,d)),
ifelse(Age > 22, sample(c("Some High School", "High School Grad", "Associates", "Bachelors", "Masters", "Professional", "Doctorate",NA),size=1,prob=c(0.085, 0.25, 0.075, 0.176, 0.072, 0.019, 0.012,d)), NA)))))
}
GenderFn <- function(d){
Gender1 <- sample(c("Male","Female","Trans", NA), 1, replace=TRUE, prob=c(0.49, 0.5, 0.01, d))
return(Gender1)
}
UserGen <- function(n,s) {
set.seed(s)
Rows <- function(y,d){
Age <- abs(AgeFn(y))
Gender <- GenderFn(d)
Education <- EduByAge(Age,d)
c(i, Age, Gender, Education)
}
df <- data.frame(matrix(NA, ncol = 4, nrow = n))
for(i in (1:n)) {
df[i,] <- Rows(y,d)
}
colnames(df) <- c("ID", "Age", "Gender", "Education")
return(df)
}