How to read txt file with multi-dimensional datasets?

Asked

Viewed 90 times

4

am with a dataset file composed of multiple dimensions in a single txt. For example,

2 3 #dimensao do primeiro dataset
1 2 3
4 5 6
4 4 #dimensao do segundo dataset
1 2 3 4 
5 6 7 8
9 10 11 12
13 14 15 16

How to read this data and form different datasets?

1 answer

7


The following function does what it wants, at least with the question data. I tried to make the function as general as possible but one never knows.

ler_txt <- function(file, path = "."){
  if(path != "."){
    old_dir <- setwd(path)
    on.exit(setwd(old_dir))
  }
  txt <- readLines(file)
  txt <- txt[nchar(txt) > 0]
  nlinhas <- length(txt)
  linha <- 1
  out_list <- list()
  while(linha < nlinhas){
    dims <- scan(text = txt[linha])
    out <- matrix(NA, nrow = dims[1], ncol = dims[2])
    for(i in seq_len(dims[1])){
      out[i, ] <- scan(text = txt[linha + i])
    }
    linha <- linha + dims[1] + 1L
    out_list[[length(out_list) + 1]] <- out
  }
  out_list
}

ler_txt(file = "dados.txt")
#[[1]]
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    4    5    6
#
#[[2]]
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    3    4
#[2,]    5    6    7    8
#[3,]    9   10   11   12
#[4,]   13   14   15   16

Browser other questions tagged

You are not signed in. Login or sign up in order to post.