Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a df like this one:

id <- c(1,1,2,2,3,3,4,4,5,5)
v1 <- c(3,1,2,3,4,5,6,1,5,4)
pos <- c(1,2,1,2,1,2,1,2,1,2)

df <- data.frame(id,v1,pos)

How can I "randomize" the values of v1 WHILE keeping the inherent order from the "Id" var and also the values of "pos" such as I get df with randomized values like this:

id  v1 pos
1   1  1
1   3  2
2   2  1
2   3  2
3   5  1
3   4  2
4   6  1
4   1  2
5   5  1
5   4  2

Above and example of resulting df with id and pos staying as originally created and v1 randomized.

Thx!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is sample what you're looking for?

df %>% 
    group_by(id) %>%
    mutate(v1 = sample(v1, size = length(v1)))
# A tibble: 10 x 3
# Groups:   id [5]
      id    v1   pos
   <dbl> <dbl> <dbl>
 1     1     3     1
 2     1     1     2
 3     2     3     1
 4     2     2     2
 5     3     4     1
 6     3     5     2
 7     4     1     1
 8     4     6     2
 9     5     5     1
10     5     4     2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...