R 填充数据帧
我是个新手,需要帮助。 我正在为我的论文制作一个基于代理的模型。 我现在所坚持的是我的人口中的出生和死亡。 我有一个数据框,包括男性、女性、年龄、怀孕、未怀孕、活着或死去。 我需要做的是 *针对n人的循环-针对每个人R 填充数据帧,r,dataframe,R,Dataframe,我是个新手,需要帮助。 我正在为我的论文制作一个基于代理的模型。 我现在所坚持的是我的人口中的出生和死亡。 我有一个数据框,包括男性、女性、年龄、怀孕、未怀孕、活着或死去。 我需要做的是 *针对n人的循环-针对每个人 用一个随机数决定性别(例如,我会这样做: library(data.table) #starting variables probMale <- .5 ageMin <- 0 ageMax <- 80 preProductiveAge <- 15 pos
- 用一个随机数决定性别(例如,我会这样做:
library(data.table) #starting variables probMale <- .5 ageMin <- 0 ageMax <- 80 preProductiveAge <- 15 postProductiveAge <- 44 probPregnant <- .3 sampleSize <- 10000 listOut <- list() for(i in 1:sampleSize){ sex <- sample(c('male', 'female'), size = 1, prob = c(probMale, 1-probMale)) age <- sample(0:80, size = 1) alive <- TRUE if(sex == 'male'){ prego <- FALSE } else if(age >= postProductiveAge){ prego <- FALSE } else if(age <= preProductiveAge){ prego <- FALSE } else{ prego <- sample(c(TRUE, FALSE), size = 1, prob = c(probPregnant, 1-probPregnant)) } listOut[[i]] <- data.frame(sex = sex, age = age, alive = alive, prego = prego) } df <- rbindlist(listOut)
库(data.table) #起始变量 probMale我的答案,没有循环:
#选择样本大小并用性别和年龄初始化数据框
samplesize无条件变量最初在
中定义。条件变量在随后的tibble()
子句中设置dplyr::mutate()
library(magrittr) person_count <- 20 range_fertile <- c(20, 45) possible_genders <- c("male", "female") possible_ages <- 1:80 pregnant_probability <- .14 tibble::tibble( gender = sample(possible_genders , person_count, replace=T), age = sample(possible_ages , person_count, replace=T), alive = TRUE ) %>% dplyr::mutate( is_fertile_age = (gender=="female") & (range_fertile[1] <= age & age <= range_fertile[2]), is_pregnant = (is_fertile_age & sample(c(T,F), person_count, prob = c(pregnant_probability, 1-pregnant_probability), replace=T)) )
库(magrittr)
谢谢,这有助于我开始。非常感谢!好的,超级干净的方法!library(magrittr) person_count <- 20 range_fertile <- c(20, 45) possible_genders <- c("male", "female") possible_ages <- 1:80 pregnant_probability <- .14 tibble::tibble( gender = sample(possible_genders , person_count, replace=T), age = sample(possible_ages , person_count, replace=T), alive = TRUE ) %>% dplyr::mutate( is_fertile_age = (gender=="female") & (range_fertile[1] <= age & age <= range_fertile[2]), is_pregnant = (is_fertile_age & sample(c(T,F), person_count, prob = c(pregnant_probability, 1-pregnant_probability), replace=T)) )