Updated 2021/04/16

The Book of R: Chapter 1, Appendix B, chapter 2.1, 2.2


Commands

print(“hello”)

  • print is the command
  • () tells R that print is a command
  • “hello” is the argument to the command
  • These are also called “functions”
print("Hello")
## [1] "Hello"
cat("hello", "world")
## hello world

Commands in R

  • Arguments can be passed flexibly
help(seq)
  • Either follow the prescribed order (ok to omit ones at the end)
seq(1,3,0.2)
##  [1] 1.0 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 2.8 3.0
  • Specify arguments with “=”
seq(1,4,length.out=3)
## [1] 1.0 2.5 4.0
  • The order is not important if you specify with =
  • seq(to=5, from=10) is the same as seq(from=10, to=5)
seq(to=5, from=10)
## [1] 10  9  8  7  6  5
seq(from=10, to=5)
## [1] 10  9  8  7  6  5

Variables

  • Variables are named places to store values
x = 5
x
## [1] 5
  • Variable names
    • Syntax is key (as in most programming languages)
    • Letters, numbers, and the dot and underscore characters, and starts with either a letter or a dot not followed by a number.
    • Reserved words (e.g. TRUE, FALSE, NA, Inf, NaN) are not syntactic names
    • Some constants are already defined variables e.g. pi
  • We declare variables in R by creating a new variable name
  • You can use any name you want, as long as you follow the syntax rules
  • Best practice is to use human readable names to help document your code e.g. use a variable name ‘patients’ instead of ‘x’

Which of these are valid R variable names?
name= “Tom”
myname# = “Alice”
_str=“test”
DNA=“ATTTCA”
sequence1=“ATTTCA”
.seq = “ATTTCA”
1seq=“ATTTCA”
= 2008
gen2str = 1

Variable assignment and types

  • We assign a value to a variable using the assignment operator
number = 5
number
## [1] 5
#note: the variable value specifies its type, not its name, 'x' can also be a number
x = 5
x
## [1] 5
number <- 5  #<- is the same as =
number
## [1] 5
string = "five"
string
## [1] "five"
number = number +1
number
## [1] 6
logical = TRUE
logical
## [1] TRUE
logical2 = T  #note: T and TRUE are equivalent (they are both TRUE)
logical2
## [1] TRUE
logical3 = FALSE
logical3
## [1] FALSE
logical4 = F  #same with F and FALSE
logical4
## [1] FALSE
#Reminder: the variable names do not tell you anything about the variable type

number = "string"
number
## [1] "string"
string = string + 1

why is there an error when you try to run this code?
Note: R only figures this out when you try to run the code, not when you’re writing it, so you need to be aware of the variable types you’re using when you’re writing code

string
## [1] "five"
  • All programming languages distinguish different variable types.
    • Numbers (integers, various non-integers)
    • Strings (=text, zero or more text characters)
    • Various others (e.g. vectors, matrices – later)

Variable types

  • Strictly speaking
    • Arithmetic operations are only defined for numbers
    • String operations are only defined for strings
  • In practice, R is lenient and converts variables if possible

Special characters

  • Special characters have special meaning in the language
    • ~!@#$%^&*(){}_+:"<>?,./;'[]-=
  • " starts and ends a string
  • \ escapes a special character e.g. \"
  • Within a string:
    • \n = newline
    • \t = tab
  • # - starts a comment line and is ignored by R
    • #my comment
    • Best practice: Use these a lot to document your code

Printing to the console/screen

x = 5
x
## [1] 5
print(x) #equivalent to above
## [1] 5
cat(x)   #similar to print, but less autoconversion
## 5
#Mixing variables within strings:
number = 5
string = "hello"
paste("Number", number, "String", string)
## [1] "Number 5 String hello"
#Here is another way to do the same thing
sprintf("Number %s String %s", number, string)
## [1] "Number 5 String hello"
#How do you print a quote?
string = "gene \"ABC\""

#Note:
print(string) #outputs `"gene \"ABC\""
## [1] "gene \"ABC\""
cat(string)  #outputs gene "ABC"
## gene "ABC"
#Here is a way to use print to get a similar result to cat in this case
print(string, quote=FALSE)
## [1] gene "ABC"
#You can use the \t string to denote a tab
cat("Separated\tby\ttabs")
## Separated    by  tabs

Exercise: Using variables (10 minutes)

  • Use the R text editor to write a program that does the following:
    • Create a variable number1 and set it to a value
    • Do the same for number2
    • Compute the sum, product and ratio of these numbers
    • Print these to the screen
  • Save your work as sum.r
  • Run it in the R console

Exercise solution (5 minutes)

File -> New File -> R script

number1 <- 5
number2 <- 15
print(number1 + number2)
print(number1 * number2)
print(number1 / number2)

File -> Save As -> Sum.R
(save in the same directory as the R notebook so that the ‘relative filepath’ below works)

source("sum.R")
## [1] 20
## [1] 75
## [1] 0.3333333

Assignment 1 hints:

Please do not submit Word documents or any rich text files as part of your assignment submission.
Each assignment should be done in its own directory, and everything needed for the assignment, including input data files, should be in that directory. You will zip up the whole directory as a tarball (see the end of assignment 1 for detailed instructions) and submit that.
Test your code! I will be unzipping your directory, and running your submitted script in the directory you submitted. You should try the same (in a new R session) prior to submitting to make sure everything works. For assignment 1, I expect two text files (as well as the relevant input and output files):
- one for the first part that includes shell commands and some commented out short answers.
- the second is the R script for the second part.
Both can be made in RStudio! File -> New File -> Shell script to make a new shell script, and Tools -> Terminal -> New Terminal to open a bash terminal to run your shell commands. Ctrl+Enter will run the current line in the console / terminal.

For loop, just for fun:

COLS=$(head -n1 gene_condition_source_id.txt | wc -w)
for X in `seq $COLS`
do
    echo line $X:
    tail -n+2 gene_condition_source_id.txt | cut -f $X | sort -u | wc -l
done
## line 1:
## 4503
## line 2:
## 4504
## line 3:
## 1407
## line 4:
## 6403
## line 5:
## 6404
## line 6:
## 8
## line 7:
## 3760
## line 8:
## 5890
## line 9:
## 537