我正在使用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)
我想对此数据进行以下更改:
-
条件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相对应的单个数据集:
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)))
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)))
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)))
final <- rbind(condition_1, condition_2, condition_3)
我的问题:
有没有一种方法可以同时获取原始数据(即“my_data”)并模拟这些条件,而不是单独模拟每个数据集?
我意识到,条件有时可能会相互矛盾——如果这些条件确实相互矛盾,那么有没有算法可以“看到”你离满足这些条件有多近?
谢谢
附加:缺失数据的可视化
library(ggplot2)
final[final == 0] <- NA
plot_missing(final)
参考文献: