How to Write a Function That Reads Files in R
Reading and Writing Data to and from R
Reading files into R
Ordinarily we will be using data already in a file that we need to read into R in club to work on information technology. R can read information from a variety of file formats—for example, files created equally text, or in Excel, SPSS or Stata. We will mainly be reading files in text format .txt or .csv (comma-separated, normally created in Excel).
To read an entire information frame directly, the external file will unremarkably have a special form
- The first line of the file should have a name for each variable in the data frame.
- Each additional line of the file has as its starting time item a row characterization and the values for each variable.
Here we employ the example dataset chosen airquality.csv and airquality.txt
Input file course with names and row labels:
Ozone Solar.R * Wind Temp Calendar month Day
1 41 ***** 190 ** seven.4 ** 67 **** 5 ** i
2 36 ***** 118 ** 8.0 ** 72 **** five ** ii
three 12 ***** 149 * 12.6 ** 74 **** five ** 3
4 xviii ***** 313 * 11.5 ** 62 **** 5 ** 4
5 NA ***** NA ** fourteen.three ** 56 **** 5 ** five
...
Past default numeric items (except row labels) are read as numeric variables. This tin be changed if necessary.
The role read.table()
can so exist used to read the data frame directly
> airqual <- read.table("C:/Desktop/airquality.txt")
Similarly, to read .csv files the read.csv() function can exist used to read in the information frame direct
[Annotation: I accept noticed that occasionally you'll need to do a double slash in your path //. This seems to depend on the machine.]
> airqual <- read.csv("C:/Desktop/airquality.csv")
In addition, you can read in files using the file.choose() function in R. After typing in this command in R, y'all tin can manually select the directory and file where your dataset is located.
- Read the airquality.csv file into R using the read.csv command.
- Read the airquality.txt file into R using the file.choose() command
Occasionally, you will need to read in data that does non already have column proper name information. For example, the dataset BOD.txt looks like this:
ane 8.three
two 10.iii
three 19.0
iv 16.0
v xv.vi
7 19.eight
Initially, there are no column names associated with the dataset. Nosotros tin use the colnames() command to assign column names to the dataset. Suppose that we want to assign columns, "Time" and "need" to the BOD.txt dataset. To do so we practice the following
> bod <- read.table("BOD.txt", header=F)
> colnames(bod) <- c("Fourth dimension","demand")
> colnames(bod)
[one] "Fourth dimension" "demand"
The first control reads in the dataset, the command "header=F" specifies that at that place are no cavalcade names associated with the dataset.
Read in the cars.txt dataset and phone call information technology car1. Make certain you utilize the "header=F" option to specify that there are no column names associated with the dataset. Next, assign "speed" and "dist" to be the commencement and 2d column names to the car1 dataset.
The two videos beneath provide a nice explanations of different methods to read data from a spreadsheet into an R dataset.
Import Data, Copy Data from Excel to R, Both .csv and .txt Formats (R Tutorial 1.3) MarinStatsLectures [Contents]
Importing Information and Working With Data in R (R Tutorial 1.four) MarinStatsLectures [Contents]
Writing Data to a File
Later working with a dataset, we might like to save it for time to come use. Before nosotros practice this, let'due south first set up a working directory and so we know where we can discover all our data sets and files subsequently.
Setting upward a Directory
In the R window, click on "File" and then on "Modify dir". You should then come across a box pop up titled "Choose directory". For this form, choose the directory "Desktop" by clicking on "Browse", so select "Desktop" and click "OK". In the time to come, y'all may want to create a directory on your computer where y'all keep your information sets and codes for this class.
Alternatively, you can utilise the setwd() function to assign as working directory.
> setwd("C:/Desktop")
To find out what your current working directory is, type
> getwd()
Setting Upwards Working Directories in R (R Tutorial one.8) MarinStatsLectures [Contents]
In R, we can write data frames easily to a file, using the write.tabular array() control.
> write.table(cars1, file=" cars1.txt ", quote=F)
The get-go argument refers to the data frame to be written to the output file, the 2nd is the name of the output file. By default R will surround each entry in the output file by quotes, so we use quote=F.
Now, permit'southward cheque whether R created the file on the Desktop, by going to the Desktop and clicking to open up the file. You should see a file with iii columns, the offset giving the index (or row number) and the other two the speed and distance. R by default creates a column of row indices. If we wanted to create a file without the row indices, we would use the command:
> write.table(cars1, file=" cars1.txt ", quote=F, row.names=F)
Datasets in R
Watch the video below for a curtailed intoduction to working with the variables in an R dataset
Working with Variables and Data in R (R Tutorial 1.5) MarinStatsLecures [Contents]
Effectually 100 datasets are supplied with R (in the parcel datasets), and others are bachelor.
To see the listing of datasets currently available use the command:
data()
We will first await at a data prepare on CO2 (carbon dioxide) uptake in grass plants available in R.
> CO2
[ Note: capitalization matters here; also: it's the letter of the alphabet O, not zero. Typing this command should display the unabridged dataset chosen CO2, which has 84 observations (in rows) and 5 variables (columns).]
To get more information on the variables in the dataset, type in
> help(CO2)
Evaluate and written report the hateful and standard deviation of the variables "Concentration" and "Uptake".
Subsetting Data in R With Square Brackets and Logic Statements (R Tutorial 1.6) MarinStatsLecures [Contents]
Source: https://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/R/R1_GettingStarted/R1_GettingStarted8.html
0 Response to "How to Write a Function That Reads Files in R"
Post a Comment