我試圖讓一個腳本來生成隨機的一組使用R.與人口統計信息的人,我希望它按行產生,而不是列,這樣的功能可以基於同一行中前一個函數的結果。我知道這可以用做對環(像我一樣下文),但for循環非常慢R.我已閱讀,你可以使用申請或而以更有效地做一個循環,但我的天堂」儘管許多嘗試失敗,但我仍然想到了如何。以下是帶有循環的功能代碼示例。我將如何做到這一點與適用或而?替代for循環的唯一行,以填補data.frame
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)
}
它看起來不像你的函數有任何從它們返回的東西。例如,'AgeFn'似乎沒有返回值。 – TARehman 2013-03-06 21:11:39
@Tarehman來自'?「function」':「如果在不調用'return'的情況下達到某個函數的結尾,則返回上一個計算過的表達式的值。」 – 2013-03-06 21:20:00
@BlueMagister Duh,我總是忘記了關於R.的錯誤。 – TARehman 2013-03-06 21:20:46