【问题标题】:Sampling different x and different sample size in R在 R 中采样不同的 x 和不同的样本大小
【发布时间】:2021-10-11 18:27:29
【问题描述】:

假设我有一张这样的桌子:

Students Equipment #
A 101
A 102
A 103
B 104
B 105
B 106
B 107
B 108
C 109
C 110
C 111
C 112

我想从数据框中的每个学生那里获取具有不同样本大小的设备 # 个样本。

例如,我想要学生“A”的 1 个设备 #、学生“B”的 2 个设备和学生“C”的 3 个设备。如何在 R 中实现这一点?

这是我现在拥有的代码,但我只打印了每个学生的 1 个设备#。

students <- unique(df$`Students`)

sample_size <- c(1,2,3)

for (i in students){

  s <- sample(df[df$`Students` == i,]$`Equipment #`, size = sample_size, replace = FALSE)

  print(s)

}

【问题讨论】:

  • 请使用以下代码提供正确的结构:- dput(df)

标签: r sample


【解决方案1】:

你已经接近了。您需要使用循环索引sample_size 向量,否则每次迭代只会获取向量中的第一项。

library(dplyr)

# set up data
df <- data.frame(Students = c(rep("A", 3),
                              rep("B", 5),
                              rep("C", 4)),
                 Equipment_num = 101:112)

# create vector of students
students <- df %>% 
  pull(Students) %>% 
  unique()

# sample and print
for (i in seq_along(students)) {
  p <- df %>% 
    filter(Students == students[i]) %>% 
    slice_sample(n = i)
  
  print(p)
}
#>   Students Equipment_num
#> 1        A           102
#>   Students Equipment_num
#> 1        B           107
#> 2        B           105
#>   Students Equipment_num
#> 1        C           109
#> 2        C           110
#> 3        C           112

reprex package (v2.0.0) 于 2021-08-06 创建

实际上this 是解决这个问题的一种更优雅、更通用的方法。

【讨论】:

    【解决方案2】:

    您可以创建一个数据框,其中包含学生信息和要采样的行。加入数据并使用sample_n 对这些行进行采样。

    library(dplyr)
    
    sample_data <- data.frame(Students = c('A', 'B', 'C'), nr = 1:3)
    
    df %>%
      left_join(sample_data, by = 'Students') %>%
      group_by(Students) %>%
      sample_n(first(nr)) %>%
      ungroup() %>%
      select(-nr) -> s
    
    s
    
    #  Students Equipment
    #  <chr>        <int>
    #1 A              102
    #2 B              108
    #3 B              105
    #4 C              110
    #5 C              112
    #6 C              111
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多