For this exercise please download this csv data file from here and place it in your working directory
If the file you want to read into R is saved as a .csv (comma separated values), use the read.csv()
function. Assign the imported data a variable name and specify the file name within the function. If you use copied quote marks for any reason, you will probably have to change them manually as they do not always copy across properly.
Input:
ghq <- read.csv("GHQ.csv")
We can also write data to a csv file (with or without modifying). The function to write to a csv file is write.csv()
. The first argument in the function is the object to be written to the file and the second argument is the file name to be used for the output. Remember to include the file extension .csv.
Input:
write.csv(ghq, "GHQ2.csv")
The data you write can be any R object (e.g. a vector, matrix, list, dataframe). Some objects write to csv better than others so have a play and you can always change the object format. In the example above we wrote out a dataframe. In the example below we write out a matrix.
Input:
a<-matrix(1:4,nrow=2,ncol=2)
a
Output:
1 3
2 4
Input:
write.csv(a,"matrix.csv")
Reading and writing Excel files into and out of R is also possible, but requires importing additional packages and complex formatting can corrupt the import. The most effective way to use R is to work with plain csv files and conduct all data transformation and analysis in the R environment and only use a spreadsheet viewer like Excel to view your data.
The function read.table(), in the base version, can import data copied to the clipboard.