Read.table storing list in Single Column

Why is the read.table function storing the data in a single column.

library(tidyverse)
library(lubridate)


# List files in the directory
file_list <- list.files(pattern = "*.txt")
file_list
filenames <- Sys.glob("*.txt")
filenames


# Create an empty list to store time series objects
ts_list <- list()

# Loop through each file
for (filename in filenames) {
  tryCatch({
    # Read data from text file
    data <- read.table(filename, skip = 10, nrows = 31, sep = "\t")
  }, error = function(e) {
    cat("Error reading file:", filename, "\n")
    print(e)
  })
  }

most likely the input its not tab delimited ?

tf <- tempfile()

writeLines("a	b	c",con = tf)

read.table(file = tf,sep="\t")
tf <- tempfile()

writeLines("a   b   c",con = tf)

read.table(file = tf,sep="\t")

in my example the top is and the bottom isnt

I also tried with space delimiter. But it returns the error as follows:

Error reading file: MDF_1964.txt 
<simpleError in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,     nmax = nrows, skip = 0, na.strings = na.strings, quiet = TRUE,     fill = fill, strip.white = strip.white, blank.lines.skip = blank.lines.skip,     multi.line = FALSE, comment.char = comment.char, allowEscapes = allowEscapes,     flush = flush, encoding = encoding, skipNul = skipNul): line 30 did not have 13 elements>

So only tab delimited works to store the data. Here's the text file I am trying to extract data from. Thank you for your time.

it seems to be neither space nor tab delimited but a fixed width format
readr package has read_fwf() to make it easier to load those kind of files.

2 Likes

Thank you so much. That worked!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.