Creating a long data format based on strings of sequences defined by colons and concatenated vectors

I have data where the identifiers of each observation are numbers stored as sequences, usually in the form of X: Y, but sometimes combined lists. I would like to tidy up the data, so each observation has its own row so that I can then use the join function to add more descriptive identifiers. I usually used the gather()from function tidyrto do this, but I had trouble unpacking the identifiers, as they are characters.

The data is as follows:

example <- data_frame(x = LETTERS[1:3], y = c("Condition 1", "Condition 2", "Condition 3"), z = c("1:3", "4:6", "c(7,9,10)"))

example
# A tibble: 3 × 3
      x           y         z
  <chr>       <chr>     <chr>
1     A Condition 1       1:3
2     B Condition 2       4:6
3     C Condition 3 c(7,9,10)

However, they do not work, and all produce NA:

as.numeric("1:3")
as.integer("1:3")
as.numeric("c(7,9,10)")
as.integer("c(7,9,10)")

, , , . X: Y , ":", :

example[1:2,] %>% 
+   separate(z, c("a", "b"), sep = ":") %>% 
+   mutate(a = as.numeric(a), b = as.numeric(b), new = list(seq(a, b)))
Error in eval(expr, envir, enclos) : 'from' must be of length 1

.

, , :

# A tibble: 9 × 3
      x           y     z
  <chr>       <chr> <dbl>
1     A Condition 1     1
2     A Condition 1     2
3     A Condition 1     3
4     B Condition 2     4
5     B Condition 2     5
6     B Condition 2     6
7     C Condition 3     7
8     C Condition 3     9
9     C Condition 3    10

?

+6
1

tidyverse

library(tidyverse)
example %>%
    group_by(x) %>%
    mutate(z = list(eval(parse(text=z)))) %>%
    unnest
#      x           y     z
#   <chr>       <chr> <dbl>
#1     A Condition 1     1
#2     A Condition 1     2
#3     A Condition 1     3
#4     B Condition 2     4
#5     B Condition 2     5
#6     B Condition 2     6
#7     C Condition 3     7
#8     C Condition 3     9
#9     C Condition 3    10
+11

Source: https://habr.com/ru/post/1016649/


All Articles