rmatrixcurly-braces

Importing .txt file in R version 4.0.0 where data is enclosed in { }


I have a .txt where the data is stored in the following format:

{{1, 2, 3, 4, 5}, {10, 9, 8, 7, 6}, {1, 3, 5, 7, 9}}

It is meant to be loaded as a 5x3 matrix, where the inner curly braces define the 3 vectors and the outer curly braces define the matrix.

For a single vector it was simple to use the scan() function to load the text as a character vector then use substr() to remove the braces, but it seems like there has to be a package or base function that reads vectors and matrices with this notation. I unfortunately have not been able to find anything on this topic after a few hours of searching.

Thanks


Solution

  • I think AllanCameron's comment is a good hint: it is close-enough to JSON that you can treat is as such (with a little bit of massaging):

    txt <- "{{1, 2, 3, 4, 5}, {10, 9, 8, 7, 6}, {1, 3, 5, 7, 9}}"
    jsonlite::fromJSON(gsub("\\}", "]", gsub("\\{", "[", txt)))
    #      [,1] [,2] [,3] [,4] [,5]
    # [1,]    1    2    3    4    5
    # [2,]   10    9    8    7    6
    # [3,]    1    3    5    7    9
    

    To do this on a file, you must first read the entire contents in, with

    txt <- paste(readLines(txtfile), collapse = "\n")
    

    Edit: code golf: jsonlite::fromJSON(chartr("{}", "[]", txt)).