bucks_fan
bucks_fan

Reputation: 1

How to read file to the list of lists in R?

Do you have any idea how to read that kind of data from txt file?

<5, <4, 3>>
<5, <6, 7>>
<1, <1, 2>>
<3, <1, 10>>
<2, <8, 8>>

The expected result is a list of lists where the rows look like:

list(
    list(5, c(4, 3))
    list(5, c(6, 7))
    list(1, c(1, 2))
    list(3, c(1, 10))
    list(2, c(1, 8))
    )

Thank you for your help

Upvotes: 0

Views: 264

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

You can do that with the help of jsonlite::fromJSON:

dat <- readLines("data.txt")
# replace '<' with '[' and '>' with ']'
dat <- gsub(">", "]", gsub("<", "[", dat))
# collapse with comma separation
dat <- paste0(dat, collapse = ",")
# encapsulates between '[' and ']'
dat <- sprintf("[%s]", dat)
# convert to R object
jsonlite::fromJSON(dat)

The result:

> str(jsonlite::fromJSON(dat))
List of 5
 $ :List of 2
  ..$ : int 5
  ..$ : int [1:2] 4 3
 $ :List of 2
  ..$ : int 5
  ..$ : int [1:2] 6 7
 $ :List of 2
  ..$ : int 1
  ..$ : int [1:2] 1 2
 $ :List of 2
  ..$ : int 3
  ..$ : int [1:2] 1 10
 $ :List of 2
  ..$ : int 2
  ..$ : int [1:2] 8 8

Upvotes: 1

Related Questions