Нужна помощь в создании случайных перестановок в R studio - PullRequest
0 голосов
/ 16 февраля 2019

Я очень плохо знаком с R и немного борюсь с тем, чтобы сориентироваться.

Мне нужно сделать случайные перестановки из моего набора данных, у меня есть 5 категорий (это возрастные классы) 10, 16, 21, 26, 36. Эти 5 категорий организованы в наблюдения групп ...например (примерно для 2000 групп):

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

Мне нужно сделать случайные перестановки этих групп.Сохранение одинакового количества значений для каждой возрастной группы (10, 16, 21, 26, 36) и сохранение одинакового количества для каждого размера группы (например, в приведенном выше примере все еще есть 5 групп, в которых всего 1 член, 3 группы из 3 членов).

Буду очень признателен за помощь.

1 Ответ

0 голосов
/ 16 февраля 2019

Вот один из способов прочитать данные, сгенерировать одну случайную перестановку и, при необходимости, сохранить ее в файл.

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.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...