Skip to content

First steps in R

    First of all, install R from here. Once R is installed you can open it and start familiarising yourself with it.

    In R you run code by selecting lines and pressing control+R (on windows) or cmd+enter (on mac). Lines starting with an ash sign (#) don’t “run”, so it’s a useful tool for writing comments or for deactivating bits of code without deleting them.

    # R is a powerful calculator! Try:
    3*2
    10/15
    sqrt(2) # square root of twosqrt() is the first R function you see! Functions apply to what's between the brackets.
    sqrt() # no argument between the brackets? R gets angry. Don't anger R.
    pi # useful
    2^3 # two to the third power
    exp(1) # this equals to e^1
    log(1) # natural log
    log(exp(1))
    log10(10) # decimal log

    You can save results. Just give them a name as follows:

    myfirstRobject <- 10/15
    myfirstRobject
    mysecondone <- 11*11
    myfirstRobject + mysecondone

    Do you want to apply a calculation to more than one number at a time? You can save the numbers in an R object called “vector”:

    somenumbers <- c(1,2,3,5,7,11)
    somenumbers*2

    A bunch of vectors together is called a matrix. Unless you give each vector in the matrix a name. In that case they form an object called a “data-frame” (namely a dataset) and each vector becomes one of the data-frame’s columns. Here’s how you create one:

    myfirstdf <- data.frame(mynumbers = somenumbers)
    # now create a new column for the data.frame:
    myfirstdf$timestwo <- myfirstdf$mynumbers * 2

    Do you want to export a data.frame? Easy peasy!

    write.csv(myfirstdf, "~/Desktop/output.csv")

    I am working on a Mac. You may have to type directories in a slightly different way in Windows.

    Did you enjoy this? Consider joining my on-line course “First steps in data analysis with R” and learn data analysis from zero to hero!