Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

R Tidyverse - Randomize by ID

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!


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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...