我正在努力寻找合适的函数,将返回指定数量的行随机拾取,没有从R语言的数据帧替换?有人能帮帮我吗?
当前回答
为了完整起见:
Dplyr还提供绘制样本的比例或分数
df %>% sample_frac(0.33)
这是非常方便的,例如,在机器学习中,当你必须做一个特定的分割比例,如80%:20%
其他回答
2021年在潮流宇宙中这样做的方式是:
library(tidyverse)
df = data.frame(
A = letters[1:10],
B = 1:10
)
df
#> A B
#> 1 a 1
#> 2 b 2
#> 3 c 3
#> 4 d 4
#> 5 e 5
#> 6 f 6
#> 7 g 7
#> 8 h 8
#> 9 i 9
#> 10 j 10
df %>% sample_n(5)
#> A B
#> 1 e 5
#> 2 g 7
#> 3 h 8
#> 4 b 2
#> 5 j 10
df %>% sample_frac(0.5)
#> A B
#> 1 i 9
#> 2 g 7
#> 3 j 10
#> 4 c 3
#> 5 b 2
由reprex包在2021-10-05创建(v2.0.0.9000)
你可以这样做:
sample_data = data[sample(nrow(data), sample_size, replace = FALSE), ]
正如@matt_b所指出的,sample_n()和sample_frac()已被软弃用,取而代之的是slice_sample()。请参阅dplyr文档。
示例来自docstring:
# slice_sample() allows you to random select with or without replacement
mtcars %>% slice_sample(n = 5)
mtcars %>% slice_sample(n = 5, replace = TRUE)
在R中从tibble类型中选择一个随机样本:
library("tibble")
a <- your_tibble[sample(1:nrow(your_tibble), 150),]
Nrow接受一个tibble并返回行数。传递给sample的第一个参数是一个从1到tibble末尾的范围。传递给sample的第二个参数是150,表示需要多少随机抽样。方括号切片指定返回索引的行。变量“a”获取随机抽样的值。
你可以这样做:
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