read.fwf error "line x did not have 5 elements" - maybe due to special characters

1.7k Views Asked by At

fwf to read fixed width text:

lines = NULL
lines[1] = '                BUTORPHANOL TARTRATE            VIAL       2 MG/ML         '
lines[2] = '                B3/AZEL AC/ZINC/B6/COPPER/FA    TABLET     600-5-500       '

write(lines, 'lines.txt')
read.fwf('lines.txt', width = c(16, 32, 11, 12, 3), as.is = T, skip = 0)
# works:
#   V1 V2                               V3          V4           V5
# 1 NA BUTORPHANOL TARTRATE             VIAL        2 MG/ML      NA
# 2 NA B3/AZEL AC/ZINC/B6/COPPER/FA     TABLET      600-5-500    NA

Adding another lines causes error:

lines[3] = '                C/B-6/NIACIN/FA/B12/HERB#192    CAPSULE    60-5-2.5MG      ' # this line causes error

write(lines, 'lines.txt')
read.fwf('lines.txt', width = c(16, 32, 11, 12, 3), as.is = T, skip = 0)

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 3 did not have 5 elements

The only think I can guess is the 3rd line has some special characters. Can somebody help please? Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

We can specify the comment.char

read.fwf('lines.txt', width = c(16, 32, 11, 12, 3), as.is = TRUE, skip = 0, comment.char="")
#  V1                               V2          V3           V4 V5
#1 NA BUTORPHANOL TARTRATE             VIAL        2 MG/ML      NA
#2 NA B3/AZEL AC/ZINC/B6/COPPER/FA     TABLET      600-5-500    NA
#3 NA C/B-6/NIACIN/FA/B12/HERB#192     CAPSULE     60-5-2.5MG   NA