Search code examples
rtidyversetidyr

Tidying arrays of numbers in R data frame


How can I tidy up the following data frame

data.frame(a  = c(1,2), values = c("[1.1, 1.2, 1.3]", "[2.1, 2.2]"))

 a          values
1 [1.1, 1.2, 1.3]
2      [2.1, 2.2]

The result should be

data.frame(a  = c(1,1,1,2,2), values = c(1.1, 1.2, 1.3, 2.1, 2.2))
  a values
 1    1.1
 1    1.2
 1    1.3
 2    2.1
 2    2.2

Solution

  • Just realized that similar to @akrun's answer it is possible to use jsonlite::fromJSON to convert the strings into vectors. This does not make any specific assumptions regarding the numbers format and does not require use of Python.

    df <- data.frame(a  = c(1,2), values = c("[1.1, 1.2, 1.3]", "[2.1, 2.2]"))
    df %>%  
        mutate(values = map(values, jsonlite::fromJSON)) %>% 
        unnest(values)