sample_n()
R语言中的函数用于从 DataFrame 中随机抽取样本。
用法: sample_n(x, n)
参数:
x:数据帧
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
这里,在上面的代码中,指定了列名。因此,在因子内应用了大小。
相关用法
- R语言 data.matrix()用法及代码示例
- R语言 with()用法及代码示例
- R语言 expand.grid()用法及代码示例
- R语言 subset()用法及代码示例
- R语言 melt()用法及代码示例
- R语言 rename()用法及代码示例
- R语言 select()用法及代码示例
- R语言 mutate()用法及代码示例
- R语言 summarise()用法及代码示例
- R语言 set.seed()用法及代码示例
- R语言 transform()用法及代码示例
注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Take Random Samples from a Data Frame in R Programming – sample_n() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。