2 | R: Programming Flashcards

1
Q

(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

a) x
b) .x
c) X1
f) helloworld
g) i
i) f

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

(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) -

A

b) ==
c) <=
e) %in%

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

(POLL)

2.3: Which of the following operators are assignment operators?
a) =
b) ==
c) ->
d) =>
e) <-
f) <=
g) «-

A

a) =
c) ->
e) <-
g) «- (superassignment)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

(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

A

c) TRUE
d) T
e) 1
h) FALSE
i) F (interpreted as FALSE)
j) 0 (interpreted as FALSE)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

(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

a) if
e) else if
f) else

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

(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

a) break
d) for
f) next
g) repeat
h) while

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

(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

A

d) function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

(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

A

c) mandatory,optional,delegation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Operators are like _______ in R but ______ can be __________left and right.

A

Operators are like functions in R but arguments can be passed left and right.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

R:

How can you declare your own operator? Give an example for the opposite of %in%

A
> '%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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

R:

What two main types of control flow are there?

A

Conditionals
Loops

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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?

A
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!!
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

R:

Is it a good idea to use loops?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

R:

what is rnorm?

A

The R function rnorm() is used for generating a vector of random numbers with a normal distribution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

R:

code for getting a matrix of 1000*100 numbers with a normal distribution.

A

> M = matrix(rnorm(100*1000), nrow=1000, ncol=100)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

R:

Functions are ________ like variables. They can be called with or without __________.

A

objects, arguments

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

R:

Structure when creating a function?

``` _____________ = ________ (__________) {
___________________
____________# if required
}
~~~

A
  • name of function
  • function
  • arguments
  • implementation
  • return(value)

``` NameOfFunction = function (Argument(s)) {
Implementation
return(value) # if required
}
~~~

18
Q

R:

How to distinguish between mandatory and optional arguments when declaring a function?

A
  • mandatory: without = sign
  • optional: with = sign and default value
19
Q

R:

Write a function for the coefficient of variation for a given numeric vector

A
myCV = function (x) {
    cv = 100 * sd(x, na.rm=TRUE) / mean(x, na.rm=TRUE)
    return(cv)
}
20
Q

R:

How can you look at code for a function in R?

A

two ways:

> body(functionName)
> functionName

(the function is an object in R!)

21
Q

R:

Must you always enter arguments in the right order?

A

You can use different argument orders if you use arg.name=value syntax:

lm(data = mydata, y ~ x, model=FALSE, 1:20)
22
Q

R:

What is ‘…’ in R?

A

Three dot / ellipsis argument

→ functions can:
- accept additional args w/o defining in signature
- be more flexible/adaptable to diff. situations.

23
Q

R:

What does dispatching functions mean? Give an example

A

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"
24
Q

R:

What is require() in R?

A

used to load packages inside functions

25
Q

R:

install a package?

load a package?

A

install:
~~~
> install.packages(‘packname’)
~~~

load:
~~~
> library(‘packname’)
~~~

26
Q

R:

What file does R load at startup?

Can you prevent this?

A
  • <HOME>/.Rprofile
    </HOME>
  • <PWD>/.Rhistory
    </PWD>
  • <PWD>/.RData

    </PWD>

prevent this:
~~~
$ R ‐‐vanilla
~~~

27
Q

R:

What is .Rprofile?

A

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!

28
Q

R:

How can you check where R looks for libraries?

A
> libPaths()
29
Q

R:

How to create a vector?

basic: ?

sequence: ?

repeated: ?

empty ?

random ?

A

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

30
Q

R:

How to create a list?

basic: ?

with names: ?

convert: ?

empty: ?

A

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)
31
Q

R:

How to create a data.frame?

basic: ?

convert: ?

empty: ?

import data: ?

A

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

32
Q

R:

How to create a matrix?

33
Q

R:

count length of a string?

A

nchar(string)

(not with new line!)

34
Q

R:

split a string?

A
strsplit(seq, 2\n")
35
Q

R:

substring?

A
substr(">hello",1,1)

[1] “>”

36
Q

(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

A

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!

37
Q

(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

A
my.xyplot <- function (x, y, col=”red”, pch=15, …){
    plot(x, y, col=col, pch=pch, …)
}
38
Q

(Quiz 1)

What is the output of the following R code?
~~~
x = 3
f = function () {
x = x + 4
}
f()
print(x)
~~~

A

3
The variable is only changed locally, so x stays 3 for the global scope.

39
Q

(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.

A

Mandatory, optional, delegation
Eg:
~~~
my.barplot <- function(x , col = ‘skyblue’, …) {
barplot(x, col = col, …)
}
~~~

40
Q

(Quiz 1)

What is the output of the following R code:
> X = 7
> print(x%%3)

A

1
%% is the modulus operator, the remainder

41
Q

(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 _____.

A

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%