显示一个随机样本,而不从主数据帧中进行子集化

Display a random sample without subsetting from the main dataframe

我有这个最终数据集,每 40 列大约 150,000 行,涵盖了我从 1932 年到 2016 年的所有潜在样本,我需要每年随机 selection 53 个样本,总共~5000 的数量。

selection 本身非常直接使用 sample() 函数获取子集,但是我需要在原始数据框中显示 selection 以便能够检查各种各样的东西。我的问题如下:

如果我编辑我的随机子集中的一个字段并将其与主字段合并,它会创建我无法删除的重复项,因为一个字段已更改,因此 R 认为这两行不是重复项。如果我不编辑任何内容,我将无法找到 selected 的行。

我现在的解决方案是合并 Excel 而不是 R 中的所有内容,应用颜色代码突出显示 selected 行并手动删除重复项。然而,它很耗时,容易出错,而且不可行,因为数据集似乎太大了,而且当我尝试时我的电脑很快就会耗尽内存...

更新:

这是一个可重现的例子:

dat <- data.frame(
  X = sample(2000:2016, 50, replace=TRUE),
  Y = sample(c("yes", "no"), 50, replace = TRUE),
  Z = sample(c("french","german","english"), 50, replace=TRUE)
)

dat2 <- subset(dat, dat$X==2000)                   #samples of year 2000
sc <- dat2[sample(nrow(dat2), 1), ]                #Random selection of 1

我想做的是直接在数据集 (dat1) 中 select,例如通过在名为 "selection" 的列中随机分配值“1”。或者,如果不可能,我如何将采样行(此处称为 "sc")合并回主数据集,但有一些表明它们已被采样的东西

注:

过去 2 年我一直在偶尔使用 R,我是一个相当缺乏经验的用户,所以如果这是一个愚蠢的问题,我深表歉意。在过去的 3 天里,我一直在漫游 Google 和 SO,但还找不到任何相关的答案。

我最近攻读了生物学博士课程,该课程要求我处理来自档案的大量数据。

EDIT: updated based on comments.

您可以添加一个列来指示某行是否是样本的一部分。所以也许可以尝试以下操作:

df = data.frame(year= c(1,1,1,1,1,1,2,2,2,2,2,2), id=c(1,2,3,4,5,6,7,8,9,10,11,12),age=c(7,7,7,12,12,12,7,7,7,12,12,12))

library(dplyr)
n_per_year_low_age = 2
n_per_year_high_age = 1
df <- df %>% group_by(year) %>% 
  mutate(in_sample1 = as.numeric(id %in% sample(id[age<8],n_per_year_low_age))) %>% 
  mutate(in_sample2 = as.numeric(id %in% sample(id[age>8],n_per_year_high_age))) %>%
  mutate(in_sample = in_sample1+in_sample2) %>%
  select(-in_sample1,-in_sample2)

输出:

# A tibble: 12 x 4
# Groups: year [2]
    year    id   age in_sample
   <dbl> <dbl> <dbl>     <dbl>
 1  1.00  1.00  7.00      1.00
 2  1.00  2.00  7.00      1.00
 3  1.00  3.00  7.00      0   
 4  1.00  4.00 12.0       1.00
 5  1.00  5.00 12.0       0   
 6  1.00  6.00 12.0       0   
 7  2.00  7.00  7.00      1.00
 8  2.00  8.00  7.00      0   
 9  2.00  9.00  7.00      1.00
10  2.00 10.0  12.0       0   
11  2.00 11.0  12.0       0   
12  2.00 12.0  12.0       1.00

接下来的操作就很简单了:

# extracting your sample
df %>% filter(in_sample==1)
# comparing statistics of your sample against the rest of the population
df %>% group_by(year,in_sample) %>% summarize(mean(id))