Reading correctly alphanumeric fields into R

Posted by gd047 on Stack Overflow See other posts from Stack Overflow or by gd047
Published on 2010-04-29T07:44:27Z Indexed on 2010/04/29 7:47 UTC
Read the original article Hit count: 379

Filed under:

A tab-delimited text file, which is actually an export (using bcp) of a database table, is of that form:

102 1   01  e113c   3224.96     12  
102 1   01  e185    101127.25   12
102 2   01  e185    176417.90   12
102A   3    01  e185    26261.03    12

I tried to import it in R with a command like

data <- read.delim("C:\\test.txt", header = FALSE, sep = "\t")

The problem is that the 3rd column which is actually a varchar field (alphanumeric) is mistakenly read as integer (as there are no letters in the entire column) and the leading zeros disappeared. The same thing happened when I imported the data directly from the database, using odbcConnect. Again that column was read as integer.

str(data)
$ code: int  1 1 1 1 1 1 6 1 1 8 ...

How can I import such a dataset in R correctly, so as to be able to safely populate that db table again, after doing some data manipulations?

© Stack Overflow or respective owner

Related posts about r