Read Fixed Width Text File in R (Example)
In this article, I’ll explain how to import a fixed width text file in the R programming language.
Table of contents:
Let’s start right away!
Example: Reading Fixed Width Text File from Website
If we want to read a fixed width text file into R (or RStudio), we can use the read.fwf function.
Within the read.fwf function, we have to specify the location of the file and the staring points of the data, i.e. from which line the data is shown and at which points new columns start.
Have a look at the following R code. It extracts data from the National Weather Service Climate Prediction Center.
data <- read.fwf( # Apply read.fwf file = url("http://www.cpc.ncep.noaa.gov/data/indices/wksst8110.for"), skip = 4, widths = c(12, 7, 4, 9, 4, 9, 4, 9, 4)) |
data <- read.fwf( # Apply read.fwf file = url("http://www.cpc.ncep.noaa.gov/data/indices/wksst8110.for"), skip = 4, widths = c(12, 7, 4, 9, 4, 9, 4, 9, 4))
Our data matrix is now stored in the data object “data”. We can have a look at the first rows of our imported data frame by using the head function:
head(data) # Print first rows # V1 V2 V3 V4 V5 V6 V7 V8 V9 # 1 03JAN1990 23.4 -0.4 25.1 -0.3 26.6 0.0 28.6 0.3 # 2 10JAN1990 23.4 -0.8 25.2 -0.3 26.6 0.1 28.6 0.3 # 3 17JAN1990 24.2 -0.3 25.3 -0.3 26.5 -0.1 28.6 0.3 # 4 24JAN1990 24.4 -0.5 25.5 -0.4 26.5 -0.1 28.4 0.2 # 5 31JAN1990 25.1 -0.2 25.8 -0.2 26.7 0.1 28.4 0.2 # 6 07FEB1990 25.8 0.2 26.1 -0.1 26.8 0.1 28.4 0.3 |
head(data) # Print first rows # V1 V2 V3 V4 V5 V6 V7 V8 V9 # 1 03JAN1990 23.4 -0.4 25.1 -0.3 26.6 0.0 28.6 0.3 # 2 10JAN1990 23.4 -0.8 25.2 -0.3 26.6 0.1 28.6 0.3 # 3 17JAN1990 24.2 -0.3 25.3 -0.3 26.5 -0.1 28.6 0.3 # 4 24JAN1990 24.4 -0.5 25.5 -0.4 26.5 -0.1 28.4 0.2 # 5 31JAN1990 25.1 -0.2 25.8 -0.2 26.7 0.1 28.4 0.2 # 6 07FEB1990 25.8 0.2 26.1 -0.1 26.8 0.1 28.4 0.3
As you can see, the imported data frame consists of nine variables containing dates and numeric values.
Note that this example is based on this thread of Stack Overflow. In the thread, you can also find alternative R codes for reading fixed width files (e.g. some code which is based on the read_fwf function of the readr package).
Video, Further Resources & Summary
In case you need further information on the topics of this article, I can recommend to have a look at the following video of my YouTube channel. In the video, I show the R programming codes of this article in RStudio:
The YouTube video will be added soon.
Besides the video, you might want to have a look at the related articles of this website:
- readLines, n.readLines & readline in R
- Read xlsx & xls Excel File in R
- scan Function in R
- readxl Package
- reader Package
- The R Programming Language
In summary: In this tutorial, I explained how to use data tables from fixed width formatted files in the R programming language. If you have any further questions, please let me know in the comments section.