简体   繁体   中英

Using apply instead of a for loop in R with condition

I have a chunk of working code where I used a for loop, but I am wondering if it would be possible to use some kind of apply function instead to make the code look nicer (and learn a good practice). The R code looks as follows

n <- 1000
curr_year <- 2020
year_of_birth <- sample((curr_year-76):(curr_year-16), n, replace=T, prob=c(rep(0.12/10,10),rep(0.22/10,10),rep(0.28/10,10),rep(0.2/10,10),rep(0.1/10,10),rep(0.08/11,11)))
years_remaining=curr_year - year_of_birth - 16
age_at_policy_begin <- rep(0, n)

for (i in 1:n) {

    age_at_policy_begin[i] <- sample(c(16:(16+years_remaining[i])), 1, replace = T)
    if(age_at_policy_begin[i] < 16){age_at_policy_begin[i] <- 16} #if years remaining is 0 -> sample from vector of length 1 samples from 0 to *value of vector* -> just set it to 16
}

I am wondering how to apply the element-wise conditional operation without using the for loop. Is it even possible?

Thank you for your help!

Something like this will work

n <- 1000
curr_year <- 2020
year_of_birth <- sample((curr_year-76):(curr_year-16), n, replace=T, prob=c(rep(0.12/10,10),rep(0.22/10,10),rep(0.28/10,10),rep(0.2/10,10),rep(0.1/10,10),rep(0.08/11,11)))


age_at_policy_begin <- sapply(curr_year - year_of_birth - 16, function(x) sample(c(16:(16+x)), 1, replace = T)) 
age_at_policy_begin <- ifelse(age_at_policy_begin < 16, 16, age_at_policy_begin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM