R/read.R

#' A read Function
#'
#' This function allows you to read file.
#' @keywords read
#' @examples
#' read()

read <- function(name){
  file = file(name , "r")
  firstline = readLines(file, n = 1)
  # Split the string with space as an separation
  firstline = strsplit(firstline, split = " ")[[1]]
  firstline = firstline[which(firstline!="")]
  # Assertion: check if 5 items; check if intergers hold
  if(length(firstline) != 5){
    stop("Error: first line fails to have exactly five items.")
  }
  # Extract the number of the column
  NCOL = as.numeric(firstline[1])
  # Extract the name of the column
  NAME_COL = firstline[2]
  # Extract the number of the row
  NROW = as.numeric(firstline[3])
  if(NCOL%%1 != 0| NROW%%1 != 0){
    stop("First line fails to contain integer value for number of rows or columns.")
  }
  # Extract the name of the row
  NAME_ROW = firstline[4]
  # Extract the title of the dataset
  TITLE = firstline[5]
  # Read the data into a vector
  data_vector = scan(file = name, skip = 1)
  # Construct a matrix using the vector
  D = matrix(data_vector, nrow = NROW, ncol = NCOL, byrow = TRUE)
  attr = list(NCOL = NCOL, NAME_COL = NAME_COL, NROW = NROW, NAME_ROW=NAME_ROW, TITLE = TITLE)
  close(file)
  return(list(attr=attr, D=D))
}
sq77/PCA7 documentation built on May 15, 2019, 4:49 p.m.