[R] Import ASCII data using a .sas program

John Fox jfox at mcmaster.ca
Wed Apr 14 22:13:34 CEST 2010


Dear Don,

What read.fwf() needs are the field widths. I think that the following will
do what you want:

> strings <- scan(what="")
1:     perstat1 $1-2
3:     linenum $3-4
5:     I_wave1 $5-5
7:     bnocost1 $6-10
9:     bnosta1 $11-12
11:     
Read 10 items

> (fields <- matrix(as.numeric(unlist(strsplit(
+     gsub("\\$", "", grep("^\\$", strings, value=TRUE)), "-"))), 
+     ncol=2, byrow=TRUE))
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    5
[4,]    6   10
[5,]   11   12
 
> (widths <- fields[,2] - fields[,1] + 1)
[1] 2 2 1 5 2

I hope this helps,
 John

--------------------------------
John Fox
Senator William McMaster 
  Professor of Social Statistics
Department of Sociology
McMaster University
Hamilton, Ontario, Canada
web: socserv.mcmaster.ca/jfox


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On
> Behalf Of Donald Catanzaro, PhD
> Sent: April-14-10 1:02 PM
> To: r-help at r-project.org
> Subject: Re: [R] Import ASCII data using a .sas program
> 
> Good Day,
> 
> I have several ASCII data files that I would like to import into R.
> They all have a SAS import file which is used to bring the data into SAS
> and I am hoping to use this to bring the data into R.  There are lots of
> variables involved and the ASCII data file is 2308 columns long so I
> would certainly prefer to figure out a smart way of converting the data
> to R.
> 
> The ASCII data is a long stream of numbers (no field separators or
> delimiters) while the SAS import file looks like:
> 
> libname mine 'c:\';
> data mine.fh4;
> infile 'd:\fh4.txt' lrecl=2309;
> input
>     perstat1 $1-2
>     linenum $3-4
>     I_wave1 $5-5
>     bnocost1 $6-10
>     bnosta1 $11-12
> 
> So SAS uses the position of the ASCII character to determine what
> variable the data should be in while the SCAN or the READ. FWF function
> of R uses the width of the column.
> 
> Does anyway have a smart and/or automated way of moving my ASCII data
> into R using this .SAS program  ?
> 
> --
> -Don
> 
> Don Catanzaro, PhD
> Landscape Ecologist
> dgcatanzaro at gmail.com
> 16144 Sigmond Lane
> Lowell, AR 72745
> 479-751-3616
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list