【问题标题】:R - subsetting original data frame: N random observations, 50% of N has ethnicity E and 50% of N has a education ER - 子集原始数据框:N 个随机观察,50% 的 N 有种族 E,50% 的 N 有教育 E
【发布时间】:2019-10-07 01:13:44
【问题描述】:

您好 Stackoverflow 用户,

我是 R 的新手,只学了几个星期。 我有一个包含 15 个关于人们特征(例如种族、教育、原籍国)的字符串变量的数据框;一排是一个人。

我如何告诉 R 创建原始数据框的一个子集,以便这个新数据框包括 N 个随机人(他们已被替换),50% 的 N 有种族 ET,50% 的 N 有教育ED? 我知道基本的 A)B)

A) 我知道如何根据herehere 的建议,随机抽取N 个观察值并进行替换。 例如:

df[sample(nrow(df), size=N, replace=TRUE), ]

B) In this other post,有一些关于如何调节随机抽奖的示例(无需替换)。

df[ sample( which( df$Ethnicity== "ET" | df$Education= "ED" ) , N ) , ]

但是,我想知道如何进行更复杂的条件抽奖,即 50% 的 N 必须有 Ethnicity ET,而 50% 的 N 必须有 Education ED。因此,在这个大小为 N 的新样本中,两个条件仅部分相交:对于某些人 Ethnicity==ET & Education==ED,对于某些人 Ethnicity!=ET & Education==ED,对于某些人 Ethnicity==ET和教育!=ED,对某些人来说 种族!=ET 和教育!=ED。

【问题讨论】:

  • @Andreas 现在我已经扩展了帖子以展示我所知道的,我在 stackoverflow 上发现的内容,并举了一些例子。但是,我在这篇文章中提出的问题非常笼统且非常复杂(鉴于我的知识有限),我看不出这些额外的信息有什么帮助。

标签: r conditional-statements subset


【解决方案1】:

一个简单的解决方案是sample 1/4 对于每个组合,希望这种组合存在:

n  <- 1e2 / 4
y <- x[c(sample(which(x$et & x$ed), n, TRUE)
         , sample(which(!x$et & x$ed), n, TRUE)
         , sample(which(x$et & !x$ed), n, TRUE)
         , sample(which(!x$et & !x$ed), n, TRUE)),]
table(y)
#       ed
#et      FALSE TRUE
#  FALSE    25   25
#  TRUE     25   25

如果存在不存在的组合,您可以使用table 获取每个组合的比例,例如:

n  <- 1e2
x  <- x[!x$et | x$ed,]
tt  <- table(x)
tt  <- tt * t(tt)
tt <- tt / rowSums(tt) 
tt <- tt / rep(colSums(tt), each=2)
tt <- round(proportions(tt)*n) #Since R 4.0.0: prop.table becomes proportions
#tt <- round(prop.table(tt)*n) #Here the target number might not be reached
y <- x[c(sample(which(!x$et & !x$ed), tt[1], TRUE)
         , sample(which(x$et & !x$ed), tt[2], TRUE)
         , sample(which(!x$et & x$ed), tt[3], TRUE)
         , sample(which(x$et & x$ed), tt[4], TRUE)),]
table(y)
#       ed
#et      FALSE TRUE
#  FALSE    50    0
#  TRUE      0   50

数据:

set.seed(7)
n  <- 1e4
x  <- data.frame(et=sample(c(TRUE,FALSE), n, TRUE, c(.25,.75)), ed=sample(c(TRUE,FALSE), n, TRUE, c(.75,.25)))

【讨论】:

  • 如果我把子样本变成一个数据框就可以了
  • 你在这里做什么:x &lt;- data.frame(et=sample(c(TRUE,FALSE), n, TRUE, c(.25,.75)), ed=sample(c(TRUE,FALSE), n, TRUE, c(.75,.25)))?
  • @Fuca26 我创建了一个可重现的示例数据集。
猜你喜欢
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2015-10-27
相关资源
最近更新 更多