R doesn’t save your output, so be sure to save code that allows you to quickly and easily replicate your work.
Annotating code helps you recall what you did earlier. R ignores any statement that starts with a “#” so you can add notes anywhere that start with this symbol.
Remember that you need to tell R where to locate your data, where to export anything you want to save.
getwd() # What is your current working directory
## [1] "/Users/ninacesare/Dropbox/R_tutorial"
setwd("/Users/ninacesare/Dropbox/R_tutorial")
list.files() # What files do I have in my working directory?
## [1] "diamonds.csv"
## [2] "diamonds.rds"
## [3] "diamonds.txt"
## [4] "diamonds.xlsx"
## [5] "misnumbered_files_old_data"
## [6] "my-code-doesnt-work.jpg"
## [7] "sample_data"
## [8] "sample_data.zip"
## [9] "section_1_why_r.html"
## [10] "section_1_why_r.Rmd"
## [11] "section_3_upload_data.html"
## [12] "section_3_upload_data.Rmd"
## [13] "section_5_exploring_data_structure.html"
## [14] "section_5_exploring_data_structure.Rmd"
## [15] "section_7_loops.html"
## [16] "section_7_loops.Rmd"
## [17] "section_9_best_practices.html"
## [18] "section_9_best_practices.Rmd"
## [19] "tweets_random.json"
Remember that R allows you to save things as ‘objects’ and recall these objects later. To see what objects you have stored in your R environment.
## First we'll need to add some stuff to our directory
diamonds<-read.csv("diamonds.csv")
mike<-c("is", "busy", "coding")
nina<-c("prefers", "to", "procrastinate")
ls()
## [1] "diamonds" "mike" "nina"
Likewise, you can remove things in your R environment.
rm("mike") # You can remove a single entity
ls()
## [1] "diamonds" "nina"
rm(list=ls(all=TRUE)) # Or you can remove everything
ls()
## character(0)
Some opinions on contested R practices:
To store data in R objects, you can use the assignment operator <-. In most cases = and <- are interchangeable. Nonetheless, it is important to know that = is actually a logical operator rather than an assignment operator.
It’s possible to attach your data to your R environment so you don’t have to call variables within it. In other words, if we type attach(diamonds) we can just type “carat” instead of “diamonds$carat.” I’d recommend not doing this. If you’re working with multiple datasets, attaching data gets confusing.
What to do if you can’t do the thing in R:
If you run into problems, Google it! There’s a 99.9% percent chance that someone else has had the same issue (and a 99.999% chance I made up that statistic). StackOverflow is a good go-to website for R help: http://stackoverflow.com/questions/tagged/r. R-bloggers also has a lot of great info: http://www.r-bloggers.com/
Remember that CRAN offers help files as well. Just type ?your.command and a help file will appear. For instance:
?read.table