R中分类变量内的随机采样

Sri*_*hna 0 r permutation sampling

假设我有一个数据框,其中包含 n 个类别的分类变量和一个数值变量。我需要随机化每个类别内的数值变量。例如,考虑下表:

Col_1           Col_2      
   A               2        
   A               5           
   A               4           
   A               8        
   B               1   
   B               4        
   B               9          
   B               7       
Run Code Online (Sandbox Code Playgroud)

当我尝试sample()R 中的函数时,它给出了考虑到这两个类别的结果。有什么函数可以得到这种输出吗?(无论有没有更换,都没关系)

Col_1           Col_2      
 A               8        
 A               4           
 A               2           
 A               5        
 B               9  
 B               7       
 B               4          
 B               1
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 5

您可以sample在组内排列数字。在基础 R 中,我们可以使用ave

df[with(df, ave(seq_len(nrow(df)), Col_1, FUN = sample)), ]

#  Col_1 Col_2
#2     A     5
#4     A     8
#1     A     2
#3     A     4
#7     B     9
#5     B     1
#8     B     7
#6     B     4
Run Code Online (Sandbox Code Playgroud)

在 中dplyr,我们可以使用sample_n

library(dplyr)
df %>% group_by(Col_1) %>% sample_n(n())
Run Code Online (Sandbox Code Playgroud)

数据

df <- structure(list(Col_1 = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L), .Label = c("A", "B"), class = "factor"), Col_2 = c(2L, 5L, 
4L, 8L, 1L, 4L, 9L, 7L)), class = "data.frame", row.names = c(NA, -8L))
Run Code Online (Sandbox Code Playgroud)