How to shuffle cells in rows

Hello, I have a question regarding shuffling data in a table. I have a table with 7 columns and 470 rows. I would need the cells in each row to be shuffled randomly and differently than in all other rows. Do you have any idea how to do that? Thank you in advance!

1 Like

Hi, welcome to the community! Thanks for your question, it was really interesting to think through. I created some pared down sample data that may be similar to yours, but I can't test it fully without a sample of your actual data. Please let me know if this fits your needs! :smiley:

library(tidyverse)

set.seed(4707)
t <- tibble(
  c1 = 1:3,
  c2 = 4:6,
  c3 = 7:9
)

t_list <- map(set_names(1:nrow(t)), ~sample(unlist(t[.x,])))

set_names(map_dfr(t_list, ~as_tibble_row(.x)), names(t))
#> # A tibble: 3 x 3
#>      c1    c2    c3
#>   <int> <int> <int>
#> 1     1     7     4
#> 2     2     8     5
#> 3     3     9     6

Created on 2021-06-18 by the reprex package (v2.0.0)

One-liner which may be more readable if you prefer this format:

library(tidyverse)

set.seed(4707)
t <- tibble(
  c1 = 1:3,
  c2 = 4:6,
  c3 = 7:9
)

1:nrow(t) %>% 
  set_names() %>% 
  map_dfr(~t[.x,] %>% 
            unlist() %>% 
            sample() %>% 
            as_tibble_row()) %>% 
  set_names(names(t))
#> # A tibble: 3 x 3
#>      c1    c2    c3
#>   <int> <int> <int>
#> 1     1     7     4
#> 2     2     8     5
#> 3     3     9     6

Created on 2021-06-18 by the reprex package (v2.0.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.