我正在努力寻找合适的函数,将返回指定数量的行随机拾取,没有从R语言的数据帧替换?有人能帮帮我吗?
当前回答
为了完整起见:
Dplyr还提供绘制样本的比例或分数
df %>% sample_frac(0.33)
这是非常方便的,例如,在机器学习中,当你必须做一个特定的分割比例,如80%:20%
其他回答
你可以这样做:
library(dplyr)
cols <- paste0("a", 1:10)
tab <- matrix(1:1000, nrow = 100) %>% as.tibble() %>% set_names(cols)
tab
# A tibble: 100 x 10
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
<int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 1 101 201 301 401 501 601 701 801 901
2 2 102 202 302 402 502 602 702 802 902
3 3 103 203 303 403 503 603 703 803 903
4 4 104 204 304 404 504 604 704 804 904
5 5 105 205 305 405 505 605 705 805 905
6 6 106 206 306 406 506 606 706 806 906
7 7 107 207 307 407 507 607 707 807 907
8 8 108 208 308 408 508 608 708 808 908
9 9 109 209 309 409 509 609 709 809 909
10 10 110 210 310 410 510 610 710 810 910
# ... with 90 more rows
上面我刚刚创建了一个10列100行的数据框架?
现在你可以用sample_n对它进行采样:
sample_n(tab, size = 800, replace = T)
# A tibble: 800 x 10
a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
<int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 53 153 253 353 453 553 653 753 853 953
2 14 114 214 314 414 514 614 714 814 914
3 10 110 210 310 410 510 610 710 810 910
4 70 170 270 370 470 570 670 770 870 970
5 36 136 236 336 436 536 636 736 836 936
6 77 177 277 377 477 577 677 777 877 977
7 13 113 213 313 413 513 613 713 813 913
8 58 158 258 358 458 558 658 758 858 958
9 29 129 229 329 429 529 629 729 829 929
10 3 103 203 303 403 503 603 703 803 903
# ... with 790 more rows
数据。表包提供了函数DT[sample(。N, M)],从数据表DT中随机抽取M行。
library(data.table)
set.seed(10)
mtcars <- data.table(mtcars)
mtcars[sample(.N, 6)]
mpg cyl disp hp drat wt qsec vs am gear carb
1: 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
2: 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
3: 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
4: 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
5: 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
6: 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
你可以这样做:
sample_data = data[sample(nrow(data), sample_size, replace = FALSE), ]
编辑:这个答案现在已经过时了,请参阅更新版本。
在我的R包中,我增强了样本,使它现在也像预期的数据帧一样:
library(devtools); install_github('kimisc', 'krlmlr')
library(kimisc)
example(sample.data.frame)
smpl..> set.seed(42)
smpl..> sample(data.frame(a=c(1,2,3), b=c(4,5,6),
row.names=c('a', 'b', 'c')), 10, replace=TRUE)
a b
c 3 6
c.1 3 6
a 1 4
c.2 3 6
b 2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6
这是通过将示例设置为S3泛型方法并在函数中提供必要的(普通的)功能来实现的。调用setMethod可以修复所有问题。原始实现仍然可以通过base::sample访问。
写一个!从JC的回答可以看出:
randomRows = function(df,n){
return(df[sample(nrow(df),n),])
}
现在,通过首先检查n是否<=nrow(df)并在出现错误时停止,使其更好。
推荐文章
- 在R函数中指定可选参数的“正确”方法
- 如何在R中选择CRAN镜像
- 生成具有给定(数值)分布的随机数
- dplyr包可以用于条件突变吗?
- 一次加载多个包
- 将缺失的日期添加到熊猫数据框架中
- 如何防止ifelse()从日期对象转化为数字对象
- 在php中生成一个随机密码
- GLSL的随机/噪声函数
- java.util.Random和java.security. securerrandom的区别
- 0到1之间的随机数?
- Pandas:索引数据帧时的多个条件-意外行为
- 使用sklearn缩放Pandas数据框架列
- read_csv . pandas中的Datetime dtypes
- 是否在函数中显式调用return