[R] data frame output almost

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Mar 20 08:10:35 CET 2004


On Fri, 19 Mar 2004, Randy Zelick wrote:

> I got three responses for help on the leading zero problem. Thank you.

Well, it seems that you didn't tell us what the actual problem was: please
consult the posting guide and its references and learn to ask the right
question.

> Alas I still don't have it working. Here are more specifics:
> 
> I read in a data file like this:
> 
> participants<-read.table("C:/Work/blah-blah")
> 
> The data file consists of the fields last name, first name, social
> security number, response score 1, response score 2 and so forth.
> 
> If in the console window I type "participants" I get something like:
> 
>      Jones  Norman  786123344 98.2 16.3
> Flintstone    Fred  111457654 10.1  8.8
>       Ugly    Butt   89733456 66.7 32.0
> 
> The problem is that the 3rd social security number is really "089733456"
> and it needs to look like that.

Did you read the help page for read.table or the `R Data Import/Export
Manual'?  Set colClasses and avoid the conversion to numeric.  You didn't
tell us you were reading a file with leading zeroes.


> None of the methods suggested seemed to work. I could make the social
> security object alone print with leading zeros, but not as part of the
> data frame.

All the solutions I have seen do work, but mine is very simple.  You need
to convert just that column (which is not what you said you wanted).

library(MASS)
hills$climb <- gsub(" ", "0", format(hills$climb))
hills

You could also use

hills$climb <- formatC(hills$climb, format="f", flag="0", digits=0, width=4)
(Martin didn't give all the details)

hills$climb <- sprintf("%04.0f", as.double(hills$climb))

In every case, printing the data frame does show leading zeroes.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list