Search code examples
rdata-cleaning

Reading a text file with double space delimiter in R


Hi I am trying to read a txt file in R but the problem is that the columns are separated by a double space. I know that the read.table can read tapped files. The problem in my case is that some character variables have a single space, i.e. "New York" so I need to separate the columns based on double space not just any space.


Solution

  • You can read the lines of your text file with the readLines function. This returns a character vector where each element corresponds to a line. You can split these strings with the strsplit function. Finally, you can combine the strings to a matrix with the rbind function.

    do.call(rbind, strsplit("filename.txt", "  "))
    

    If you need a data frame, you can convert the matrix with the function as.data.frame.