Вот один из способов прочитать данные, сгенерировать одну случайную перестановку и, при необходимости, сохранить ее в файл.
library("tidyverse")
input <- "10,10,16,21
16,16,16
36
21
21,26
21,10
10,10,16
16
21
26,16
16,16,16,16,21,16,10
16,21,16
26
"
read_data <- function(input) {
data <-
read_lines(input) %>% # Or read them from a text file with `read_lines(filename)`
enframe("group", "category") %>% # Convert to a data frame with two columns:
# "name": the group ID, which is the same as the row number
# "value": the sequence of sightings as a string
mutate(category = str_split(category, ",")) %>% # Split "10,16,26" into c("10","16","26"), etc.
unnest() %>% # "Unfold" the data frame so that each row is a group ID and an element
# e.g., c("10","16","26") will unnest into three rows.
mutate(category = as.integer(category)) # Convert "10" into 10, might not be strictly necessary
data
}
permute_data <- function(data) {
data %>%
mutate(shuffled = sample(category, n(), replace = FALSE)) %>% # Keep the IDs ordered,
# shuffle the observations.
group_by(group) %>% # Now a group originally with 3 elements is
summarise(shuffled = paste(shuffled, collapse = ",")) # matched with 3 randomly selected elements.
# Join those together in the input format.
}
data <- read_data(input)
data2 <- permute_data(data) # Permute the data, once or multiple times
# The result is a data frame with the original groups in the "name" column,
# and the shuffled groups in the "shuffled" column
data2
data2$shuffled %>% write_lines("shuffled.txt") # Save just the shuffled column to a new file.