📜  在 R 编程中从数据帧中抽取随机样本 – sample_n()函数

📅  最后修改于: 2022-05-13 01:55:20.856000             🧑  作者: Mango

在 R 编程中从数据帧中抽取随机样本 – sample_n()函数

R 语言中的sample_n()函数用于从数据框中获取随机样本样本。

示例 1:

# R program to collect sample data
# from a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
  
# Printing three rows 
sample_n(d, 3) 

输出:

name age ht school
1  Chaman   9 NA     no
2    Abhi   7 46    yes
3 Bhavesh   5 NA    yes

示例 2:

# R program to collect sample data
# from a data frame
  
# Loading library 
library(dplyr)
    
# Create a data frame
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
  
# Printing three rows 
sample_n(d, 3, fac = "name")$name

输出:

[1] Chaman  Bhavesh Dimri  
Levels: Abhi Bhavesh Chaman Dimri

这里,在上面的代码中,指定了列名。因此,大小应用于因子内。