代码之家  ›  专栏  ›  技术社区  ›  stats_noob

R: 是否可以根据以下条件模拟数据?

  •  0
  • stats_noob  · 技术社区  · 3 年前

    我正在使用R编程语言。假设我有以下数据集:

    set.seed(123)
    
    var_1 <- rnorm(1000, 10, 1)
    var_2 <- rnorm(1000, 10, 5)
    var_3 <- rnorm(1000, 10, 10)
    
    my_data <- data.frame(var_1, var_2, var_3)
    my_data$group <- as.factor(sample(LETTERS[1:4], 100, replace=TRUE, 
                                      prob=c(0.25, 0.3, 0.5, 0.15)))
    my_data$id <- 1:nrow(my_data)
    
    #       var_1     var_2     var_3 group id
    # 1  9.439524  6.447967 31.988103     C  1
    # 2  9.769823 11.284419 23.124130     A  2
    # 3 11.558708  8.766541  7.348549     C  3
    # 4 10.070508  8.262287 15.431941     C  4
    # 5 10.129288  5.241907  5.856601     C  5
    # 6 11.715065  9.774861  5.237531     A  6
    

    我想对此数据进行以下更改:

    • 条件1: 对于“组=A或组=B”的所有行,将var_1的至少10%的值随机替换为0,将var_2的至少15%的值随机替代为0

    • 条件2: 对于“组=B或组=C”的所有行,随机将var_1的至少20%的值替换为0,将var_3的至少20%值替换为零

    • 条件3: 对于“组=A或组=C”的所有行,随机将var_1的至少25%的值替换为0,将var_2的至少25%值替换为零

    • 条件4(可选): 0在整个数据中的总体百分比应小于15%

    我知道如何模拟与条件1、条件2和条件3相对应的单个数据集:

    #condition 1
    
    a <- rnorm(100, 10, 1)
    b <- rnorm(100, 10, 5)
    c <- rnorm(100, 10, 10)
    
    condition_1 <- data.frame(a, b, c)
    
    perc <- c(0.1, 0.15, 0)
    
    condition_1[] <- Map(function(x, y) {
      x[sample(seq_along(x), length(x) * y)] <- 0
      x
    }, condition_1, perc)
    
    condition_1$group <- as.factor(sample(LETTERS[1:2], 100, replace=TRUE, 
                                          prob=c(0.5, 0.5)))
    
    #condition 2
    
    a <- rnorm(100, 10, 1)
    b <- rnorm(100, 10, 5)
    c <- rnorm(100, 10, 10)
    
    condition_2 <- data.frame(a, b, c)
    
    perc <- c(0.2, 0, 0.2)
    
    condition_2[] <- Map(function(x, y) {
      x[sample(seq_along(x), length(x) * y)] <- 0
      x
    }, condition_2, perc)
    
    group <- c("B", "C")
    
    condition_2$group <- as.factor(sample(group, 100, replace=TRUE, prob=c(0.5, 0.5)))
    
    #condition 3
    
    a <- rnorm(100, 10, 1)
    b <- rnorm(100, 10, 5)
    c <- rnorm(100, 10, 10)
    
    condition_3 <- data.frame(a, b, c)
    
    perc <- c(0.25, 0.25, 0)
    
    condition_3[] <- Map(function(x, y) {
      x[sample(seq_along(x), length(x) * y)] <- 0
      x
    }, condition_3, perc)
    
    group <- c("A", "C")
    
    condition_3$group <- as.factor(sample(group, 100, replace=TRUE, prob=c(0.5, 0.5)))
    
    #join all data together
    
    final <- rbind(condition_1, condition_2, condition_3)
    

    我的问题: 有没有一种方法可以同时获取原始数据(即“my_data”)并模拟这些条件,而不是单独模拟每个数据集?

    我意识到,条件有时可能会相互矛盾——如果这些条件确实相互矛盾,那么有没有算法可以“看到”你离满足这些条件有多近?

    谢谢

    附加:缺失数据的可视化

    library(ggplot2)
    
    final[final == 0] <- NA
    
    #source for "plot_missing()" function from here: https://github.com/jevgenij-p/blog/blob/master/Missing%20Values%20Plot/MissingValues.R
    
    plot_missing(final)
    

    enter image description here

    参考文献:

    0 回复  |  直到 3 年前