簡體   English   中英

在R中的表中的兩列數據之間隨機選擇

[英]randomly selecting between two columns of data in a table in R

因此,我有一張表格,其中包含有關參加兩個測試版本的主題的數據。 我想做的是編寫一些代碼,該代碼使我能夠隨機選擇要包含在最終表中的測試版本以及要舍棄的測試版本。 以下是一些示例數據:

ID     test1    test2

38762   21       36
37874   17       20
37813   15       17
37738   23       31
37470   25       36
37308   31       32
37039   25       16
36045   16        9

我需要使它盡可能接近隨機性,因此我們將不勝感激。

提前致謝

編輯:所需的輸出:

row.names   ID  test1
    67  38762   21
    218 36045   16


row.names   ID  test2
    108 37874   20
    114 37813   17
    117 37738   31
    140 37470   36
    152 37308   32
    175 37039   16

您可能會這樣:首先將三列設為數據框(如果尚未創建)。 然后根據您生成的0和1的隨機向量對該數據幀進行子集化。

 df <- cbind(ID, test1, test2)
 #make vector of 0s and 1s of the length = number of rows of df 
 ran <- sample(c(0,1), nrow(df), replace = TRUE) 

 group1 <- subset(subset(df, select = c(ID, test1)), subset = ran == 0)
 group2 <- subset(subset(df, select = c(ID, test2)), subset = ran == 1)
> df=NULL
> df$ID=sample(38700:38800,10,F)
> df$test1=sample(15:25,10,F)
> df$test2=sample(15:35,10,F)
> df=as.data.frame(df)
> df
      ID test1 test2
1  38784    24    19
2  38747    15    15
3  38791    16    34
4  38721    25    32
5  38769    20    23
6  38706    21    26
7  38702    17    29
8  38761    22    28
9  38763    19    25
10 38740    23    16
> df$ran=sample(2,nrow(df),T)
> df$test=ifelse(df$ran==1,df$test1,df$test2)
> df
      ID test1 test2 ran test
1  38784    24    19   1   24
2  38747    15    15   1   15
3  38791    16    34   1   16
4  38721    25    32   1   25
5  38769    20    23   1   20
6  38706    21    26   1   21
7  38702    17    29   2   29
8  38761    22    28   1   22
9  38763    19    25   1   19
10 38740    23    16   2   16
> df$testchosen=ifelse(df$ran==1,"test1","test2")
> df
      ID test1 test2 ran test testchosen
1  38784    24    19   1   24      test1
2  38747    15    15   1   15      test1
3  38791    16    34   1   16      test1
4  38721    25    32   1   25      test1
5  38769    20    23   1   20      test1
6  38706    21    26   1   21      test1
7  38702    17    29   2   29      test2
8  38761    22    28   1   22      test1
9  38763    19    25   1   19      test1
10 38740    23    16   2   16      test2
> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM