Reading .txt file as a single column

I have a text file, which has only one column. Many observations have spaces. How can I read the file as it is? For example, I want to read the example.txt(given below) as df, which will have only one column.

library(dplyr)
# Example data
df <- tibble(x = c("121000000000 99        ", 
                   "005454652222      11111", 
                   "                0007234", 
                   "  defghijk   00     000"))
df
#> # A tibble: 4 x 1
#>   x                        
#>   <chr>                    
#> 1 "121000000000 99        "
#> 2 "005454652222      11111"
#> 3 "                0007234"
#> 4 "  defghijk   00     000"
write.table(df,
            "example.txt", # I want to read this text file
            col.names = FALSE,
            row.names = FALSE,
            quote = FALSE)

Created on 2022-01-27 by the reprex package (v2.0.0)

From here you can use stringr::str_trim() to close up the leading and trailing spaces and stringr::str_split() to tease out the lines with multiple values.

# Example data
DF <- tibble::tibble(x = c("121000000000 99        ", 
                   "005454652222      11111", 
                   "                0007234", 
                   "  defghijk   00     000"))

write.table(DF,
            "example.txt", # I want to read this text file
            col.names = FALSE,
            row.names = FALSE,
            quote = FALSE)

object <- readLines("/home/roc/projects/demo/example.txt")

object
#> [1] "121000000000 99        " "005454652222      11111"
#> [3] "                0007234" "  defghijk   00     000"
1 Like

@technocrat many thanks for the solution and advice!

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.