R
Saving/loading data
Often, you will need to import/export your data to/from R, for example when first analyzing it in spreadsheet editor or in order to send your data to someone else.
One efficient way of doing that is using the comma-separated values format (.csv). In CSV files, columns are separated by commas (or semicolons, depending on your regional setting). The main advantage of the CSV format is its wide compatibility with other software.
In order to load your data stored in a CSV file, use the read.csv() function. As you will want to use the data, you should store the read values immediately in a variable like this:data <- read.csv(file.choose())
or like this (replacing the path with the relevant one):data <- read.csv("C:/projects/data.csv")
NOTE: If your spreadsheet editor uses semicolons to separate the columns, use read.csv2().
In the first case, a dialog window will open asking you to select a file to open, giving you the flexibility to choose the relevant file every time you run the script. In the second case, the path to the data is specifically written in the command. This a good option for files which you open every time you run your script.
An important argument which is often given to the function read.csv() is header. This argument can have the values T or F, and specifies whether there is a header in the file – a first row with the names of the columns. If this argument is set to T, the first row will be used to infer names of the columns. If it is set to F, it is assumed that there are no column names in the CSV file. An example usage for a file without a header would be:data <- read.csv(file.choose(), header=F)
EXERCISE:
Load in the example data. Make sure that R recognizes the header.
After you have finished your work with the data, you can export it in a CSV file using the write.csv() function. This function expects you to specify what you want to write and where, like this:write.csv(data, file.choose())
Notice that we are not using the assignment sign here, since we are not storing anything in R’s memory.