English 中文(简体)
随意从群体中选择价值观顺序
原标题:Select sequences of values from groups at random

这里的数据是:

df <-
  data.frame(group = c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4),
             value = LETTERS[1:20])

我需要从每个组随机选择四个数值的顺序,以<代码>dplyr。 选定的数值应与数据相同,两者之间不应有差距。

期望的结果可能如下:

   group value
1      1     A
2      1     B
3      1     C
4      1     D
6      2     F
7      2     G
8      2     H
9      2     I
11     3     K
12     3     L
13     3     M
14     3     N
17     4     Q
18     4     R
19     4     S
20     4     T

   group value
1      1     A
2      1     B
3      1     C
4      1     D
5      2     E
6      2     F
7      2     G
8      2     H
10     3     J
11     3     K
12     3     L
13     3     M
17     4     Q
18     4     R
19     4     S
20     4     T

这是我解决的:

set.seed(23)
df %>% 
  group_by(group) %>% 
  mutate(selected = sample(0:1, size = n(), replace = TRUE)) %>% 
  filter(selected == 1)

然而,我无法说明如何在一行中产生4人,在他们之前或之后产生零。

最佳回答

我们可以<条码>。 (minus three) in the group, volume one, and Add0:3 to that to selected which rows wemain.

set.seed(42)
df %>%
  group_by(group) %>%
  filter(row_number() %in% c(sample(max(1, n()-3), size=1) + 0:3)) %>%
  ungroup()
# # A tibble: 16 × 2
#    group value
#    <dbl> <chr>
#  1     1 A    
#  2     1 B    
#  3     1 C    
#  4     1 D    
#  5     2 E    
#  6     2 F    
#  7     2 G    
#  8     2 H    
#  9     3 J    
# 10     3 K    
# 11     3 L    
# 12     3 M    
# 13     4 Q    
# 14     4 R    
# 15     4 S    
# 16     4 T    
问题回答

暂无回答




相关问题
Weighted random numbers

I m trying to implement a weighted random numbers. I m currently just banging my head against the wall and cannot figure this out. In my project (Hold em hand-ranges, subjective all-in equity ...

Comprehensive information about hash salts

There are a lot of questions about salts and best practices, however most of them simply answer very specific questions about them. I have several questions which feed into one another. Assuming a ...

Generate unique names?

I am working on a php site in which we have to upload images from users.i have to rename that file for preventing conflicts in the name of the image. uniqid(rand(), true); and adding a large random ...

How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

热门标签