2 | R: Programming Flashcards
(POLL)
2.1: Which of the following symbols are valid variable names
a) x
b) .x
c) X1
d) 1X
e) hello world
f) helloworld
g) i
h) in
i) f
j) for
a) x
b) .x
c) X1
f) helloworld
g) i
i) f
(POLL)
2.2: Which of the following operators are logical operators so return either TRUE or FALSE?
a) =
b) ==
c) <=
d) <-
e) %in%
f) %*%
g) +
h) -
b) ==
c) <=
e) %in%
(POLL)
2.3: Which of the following operators are assignment operators?
a) =
b) ==
c) ->
d) =>
e) <-
f) <=
g) «-
a) =
c) ->
e) <-
g) «- (superassignment)
(POLL)
2.4: Which of the following values are in R of type boolean?
a) true
b) True
c) TRUE
d) T
e) 1
f) false
g) False
h) FALSE
i) F j) 0
c) TRUE
d) T
e) 1
h) FALSE
i) F (interpreted as FALSE)
j) 0 (interpreted as FALSE)
(POLL)
2.5: Which of the following terms are valid R conditionals?
a) if
b) fi
c) elsif
d) elif
e) else if
f) else
g) when
a) if
e) else if
f) else
(POLL)
2.6: Which of the following terms are valid loop expressions in R?
a) break
b) continue
c) do
d) for
e) foreach
f) next
g) repeat
h) while
a) break
d) for
f) next
g) repeat
h) while
(POLL)
2.7) Which is the keyword to declare a function in R?
a) def
b) fun
c) func
d) function
e) none, we just use the assignment operator
d) function
(POLL)
2.8: What is the prefered order of arguments in the function declaration?
a) delegation,mandatory,optional
b) optional,mandatory,delegation
c) mandatory,optional,delegation
d) mandatory,delegation,optional
IMPORTANT
c) mandatory,optional,delegation
Operators are like _______ in R but ______ can be __________left and right.
Operators are like functions in R but arguments can be passed left and right.
R:
How can you declare your own operator? Give an example for the opposite of %in%
> '%ni%' <- Negate(‘%in%’) > LETTERS[1:8] [1] "A" "B" "C" "D" "E" "F" "G" "H" > LETTERS[1:8] %in% c('B','C','D') [1] FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE > LETTERS[1:8] %ni% c('B','C','D') [1] TRUE FALSE FALSE FALSE TRUE TRUE TRUE TRUE
R:
What two main types of control flow are there?
Conditionals
Loops
R:
Give an example for a loop using repeat and break, to print the numbers 3, 4 and 5.
Is there a better way to do this?
x=3 repeat { print (x); x=x+1; if (x > 5) { break } }
better:
~~~
x=3
for (i in x:5) {
print(i)
} # we like that most!!
~~~
R:
Is it a good idea to use loops?
Avoid loops in R if you can! (R < 4 ?)
* looping in R can be sometimes quite slow
* use vector operations if possible
* you can start with a loop but if ready: think about a vector operation
R:
what is rnorm?
The R function rnorm() is used for generating a vector of random numbers with a normal distribution.
R:
code for getting a matrix of 1000*100 numbers with a normal distribution.
> M = matrix(rnorm(100*1000), nrow=1000, ncol=100)
R:
Functions are ________ like variables. They can be called with or without __________.
objects, arguments
R:
Structure when creating a function?
``` _____________ = ________ (__________) {
___________________
____________# if required
}
~~~
- name of function
- function
- arguments
- implementation
- return(value)
``` NameOfFunction = function (Argument(s)) {
Implementation
return(value) # if required
}
~~~
R:
How to distinguish between mandatory and optional arguments when declaring a function?
- mandatory: without = sign
- optional: with = sign and default value
R:
Write a function for the coefficient of variation for a given numeric vector
myCV = function (x) { cv = 100 * sd(x, na.rm=TRUE) / mean(x, na.rm=TRUE) return(cv) }
R:
How can you look at code for a function in R?
two ways:
> body(functionName)
> functionName
(the function is an object in R!)
R:
Must you always enter arguments in the right order?
You can use different argument orders if you use arg.name=value syntax:
lm(data = mydata, y ~ x, model=FALSE, 1:20)
R:
What is ‘…’ in R?
Three dot / ellipsis argument
→ functions can:
- accept additional args w/o defining in signature
- be more flexible/adaptable to diff. situations.
R:
What does dispatching functions mean? Give an example
R Dispatching functions
old S3 approach (1988) - still most popular
> var = 3 > class(var) [1] "numeric" > class(var) = "test" ; > class(var) [1] "test" > print.test = function (x) { print (paste("this is the method of test:",x)) } > print(var) [1] "this is the method of test: 3"
R:
What is require() in R?
used to load packages inside functions
R:
install a package?
load a package?
install:
~~~
> install.packages(‘packname’)
~~~
load:
~~~
> library(‘packname’)
~~~
R:
What file does R load at startup?
Can you prevent this?
- <HOME>/.Rprofile
</HOME> - <PWD>/.Rhistory
</PWD> - <PWD>/.RData
</PWD>
prevent this:
~~~
$ R ‐‐vanilla
~~~
R:
What is .Rprofile?
A script that R executes every time you launch an R session. You can use it to automatically load packages, etc ….
Be careful to not overuse .Rprofile: programs which use functions declared there will not work if you use them in your script files on other computers or for other users‼
Sessions with old .RData files might harm script development!
R:
How can you check where R looks for libraries?
> libPaths()
R:
How to create a vector?
basic: ?
sequence: ?
repeated: ?
empty ?
random ?
basic:
v1 <- c(1, 2, 3, 4, 5)
sequence:
v2 <- seq(1, 10, by = 2) # Creates: 1, 3, 5, 7, 9
v3 <- 1:10 # Creates: 1, 2, 3, …, 10
repeated:
v4 <- rep(1:3, times = 2) # Repeats (1,2,3) twice: 1,2,3,1,2,3
v5 <- rep(1:3, each = 2) # Repeats each element twice: 1,1,2,2,3,3
empty
v6 <- vector(“numeric”, length = 5) # Creates: 0, 0, 0, 0, 0
random
v7 <- rnorm(5) # 5 random numbers from normal distribution
v8 <- runif(5, min = 0, max = 10) # 5 random numbers from uniform distribution
R:
How to create a list?
basic: ?
with names: ?
convert: ?
empty: ?
basic:
my_list <- list(1, "hello", TRUE, c(2, 3, 4))
with names:
my_named_list <- list(name = "Alice", age = 25, scores = c(90, 85, 88))
convert:
my_list <- as.list(c(10, 20, 30)) list_from_df <- split(df, seq(nrow(df)))
empty:
empty_list <- vector("list", length = 3)
R:
How to create a data.frame?
basic: ?
convert: ?
empty: ?
import data: ?
basic: ?
df <- data.frame(
Name = c(“Alice”, “Bob”, “Charlie”),
Age = c(25, 30, 35),
Score = c(90, 85, 88)
)
convert: ?
df <- as.data.frame(matorlist)
empty: ?
empty_df <- data.frame(Name = character(), Age = numeric(), Score = numeric())
import data
df <- read.csv(“data.csv”, header = TRUE, sep = “,”, stringsAsFactors = FALSE)
df <- read.table(“data.txt”, header = TRUE, sep = “\t”) # Tab-separated file
R:
How to create a matrix?
R:
count length of a string?
nchar(string)
(not with new line!)
R:
split a string?
strsplit(seq, 2\n")
R:
substring?
substr(">hello",1,1)
[1] “>”
(Quiz 1)
Which of the following text strings are valid variable names
a. In
b. that_is_a_stupid_varname.but_I_like_it.
c. .secret
d. break
e. 9k
f. IIn
b. that_is_a_stupid_varname.but_I_like_it.
c. .secret - a hidden variable starting with a dot, that’s ok
f. IIn - two I’s, not a keyword
→ Variable names can’t start with numbers and can’t be keywords!
(Quiz 1)
Complete the missing code for an implementation of a function which should mimic the default plot function for two numerical variables, but per default with red rectangles as plotting characters.
~~~
_______ <- _______ (____, ____, ____, ____, ____){
plot(x, y, col=col, pch=pch, …)
}
~~~
IMPORTANT
my.xyplot <- function (x, y, col=”red”, pch=15, …){ plot(x, y, col=col, pch=pch, …) }
(Quiz 1)
What is the output of the following R code?
~~~
x = 3
f = function () {
x = x + 4
}
f()
print(x)
~~~
3
The variable is only changed locally, so x stays 3 for the global scope.
(Quiz 1)
What is the most appropriate order for defining your function arguments?
* Optional, mandatory, delegation
* Delegation, optional, mandatory
* Mandatory, optional, delegation
Give an example using barplot.
Mandatory, optional, delegation
Eg:
~~~
my.barplot <- function(x , col = ‘skyblue’, …) {
barplot(x, col = col, …)
}
~~~
(Quiz 1)
What is the output of the following R code:
> X = 7
> print(x%%3)
1
%% is the modulus operator, the remainder
(Quiz 1)
Custom operators in R _____ be declared using the _____ signs. This is a possible own operators which _____ be declared in R by the user _____.
Custom operators in R can be declared using the percentage signs. This is a possible own operators which can be declared in R by the user %I%