user1787675
user1787675

Reputation: 1121

How to keep the zeros in the characters when I use the function read.fwf in R?

My code is

ff <- tempfile()
cat(file=ff,"11220011003","11220011003",sep="\n");
x <- read.fwf(ff,widths=c(2,2,4,3))

And I get a matrix like this:

11 22 11  3
11 22 11  3

But the result I want is

11 22 0011 003
11 22 0011 003

How should I correct my code to get the matrix I want?

Upvotes: 0

Views: 245

Answers (2)

Ali
Ali

Reputation: 9850

Try this:

ff <- tempfile()
cat(file=ff,"11220011003","11220011003",sep="\n");
x <- read.fwf(ff,widths=c(2,2,4,3), colClasses = "character")
x
#   V1 V2   V3  V4
# 1 11 22 0011 003
# 2 11 22 0011 003

Then you may cast your desired columns to integer using as.integer()

Upvotes: 2

Joshua Ulrich
Joshua Ulrich

Reputation: 176698

read.fwf returns a data.frame, not a matrix; and it seems to be returning a data.frame of numeric vectors. If you want a data.frame of character vectors instead, specify colClasses (see ?read.table).

x <- read.fwf(ff,widths=c(2,2,4,3), colClasses=rep("character",4))
x
#   V1 V2   V3  V4
# 1 11 22 0011 003
# 2 11 22 0011 003
str(x)
# 'data.frame':   2 obs. of  4 variables:
#  $ V1: chr  "11" "11"
#  $ V2: chr  "22" "22"
#  $ V3: chr  "0011" "0011"
#  $ V4: chr  "003" "003"

Upvotes: 3

Related Questions