Loading Data into R
One way to use R is by typing your data directly into R this is called "hard coding". A more dynamic approach is to load data from an external data source such as .csv files or databases.
Importing Text Files: CSV & TXT
CSV (Comma-Separated Values) is a plain-text file that contains data. As the name reveals, CSV files use a comma to separate values. Some files might be named ".csv" without actually using a comma and on the other hand ".txt" files may use a comma as a separator. At the end these files are all plain text and there is no validation if a file adheres to a "csv" standard.
patient_data.csv
Name, Sex, Age, Blood.type
Joe J., m, 34, A+
Laura M., f, 56, AB+
Isobel P., f, 23, 0+
Nina W., f, 18, B-
The first row of the file contains the column names.
With dir()
, you can list existing files in your working directory.
utils
& read.csv()
To import a CSV file, you can use the read.csv()
function.
It is included with the utils
package, which is loaded by default when you start R, so you don't need to install anything.
# Import patient_data.csv: patients
patients <- read.csv("patient_data.csv")
# Print the structure of patients
str(patients)
output:
'data.frame': 4 obs. of 4 variables:
$ Name : chr "Joe J." "Laura M." "Isobel P." "Nina W."
$ Sex : chr "m" "f" "f" "f"
$ Age : int 34 56 23 18
$ Blood.type: chr "A+" "AB+" "0+" "B-"