Andrea
Andrea

Reputation: 111

How read txt file with special separator and carriage return?

When import txt file in r I have only one line with all values and not two lines. I think the problem is this #@#@#. Could you help me to solve the problem?

Example of the file:

A'~'40337463'~''~'1403289'~'4620851'~'21'~''~'STDLONG'~'A-'~'A-'~'2020-06-08 15:05:59'~''~''~''~''~''~''~''~''~'EU'~''~'New Rating'~''~''~'2023-06-28 00:00:00'~''~''~'DE000A254Z26#@#@#A'~'40337464'~''~'1403282'~'4620842'~'21'~''~'STDLONG'~'BBB+'~'BBB+'~'2020-06-08 15:11:49'~''~''~''~''~''~''~''~''~'EE'~''~'New Rating'~''~''~'2030-12-31 00:00:00'~''~''~'US776743AJ55#@#@#

dd <- data.table::fread("200610-204642spRatingDataNoCUSIP.txt", sep = "~", header = F)

Output:

enter image description here

Upvotes: 2

Views: 644

Answers (1)

Martin Gal
Martin Gal

Reputation: 16988

One basic approach could be editing your .txt-file and replacing those #@#@# with line breaks.

Another approach using readr and stringr:

df <- read_lines("test.csv") %>%
  str_split("#@#@#", simplify=TRUE) %>%
  read_delim(delim="~", col_names=FALSE) %>%
  mutate(across(everything(), str_remove_all, pattern="'"))

I named the file test.csv, change it accordingly. Acutally I'm not sure if this works with large files, but you could give it a try.

Upvotes: 2

Related Questions