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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。