This lesson is being piloted (Beta version)

Basic of R

Overview

Teaching: 5 min
Exercises: 0 min
Questions
  • how to do basic arithmetics

  • how to initialize a variable

  • how to get help

Objectives
  • R built-in function

Input to R

> rm(list=ls())

Using R as calculator

When using R as a calculator, the order of operations is the same as you would have learned back in school.

From highest to lowest precedence:

a <- (1+2)*3-4^5
b <- sin(1)+log10(20)*exp(2)

Compare in R

1==1

Assign Variables

a <- 1
b = 2

Note that assignment does not print out value to R console. It save the variable in Environment section: image

a
print(a)

The output will be like this:

> a
[1] 1
> print(a)
[1] 1

But not to worry about the [1] in front. We will be learning about that in the later part

Working directory

One important step in R is to define the working directory. It is particularly useful when you are working with files in the working directory and working in Linux environment in Palmetto:

# print working directory
getwd()
# set working directory
setwd('C:/R/') # for Windows
setwd('/user/home/R') # for Macs

Seeking Help

In order to look for help files for function:

?rnorm
help(rnorm)
str(rnorm)

The help section will display:

image

Key Points

  • Use RStudio to write and run R programs.

  • R has the usual arithmetic operators and mathematical functions.

  • Use <- to assign values to variables.

  • Use ls() to list the variables in a program.

  • Use rm() to delete objects in a program.

  • Use sessionInfo() to get detail of the current loaded environmemt and packages