Which expression(s) equal to TRUE? (x equals 5) a ) T R U E | F A L S E b ) x > 5 c ) F A L S E & T R U E d ) x < = 1 | x > 5 Answer: a) and d) What is the value of y at the end of the loop if it was 0 and the beginning? How many iterations of the loop occurred? while (y <= 10) { y <- 2*y + 3} Answer: y = 21; the loop ran 3 times.
An introduction to WS 2019/2020
- Dr. Noémie Becker
- Dr. Eliza Argyridou
Special thanks to:
- Dr. Sonja Grath for addition to slides
Basics of Algorithmics in R
3
What you should know after days 7 & 8
Review: Data frames and import your data Conditional execution in R
- Logic rules
- if(), else(), ifelse()
- Example from day 1
Loops Executing a command from a script Writing your own functions How to avoid slow R code 4
Basics
Syntax: m y f u n <
- f
u n c t i
- n
( a r g 1 , a r g 2 , … ) { c
- m
m a n d s } Example: We want to define a function that takes a DNA sequence as input and gives as output the GC content (proportion of G and C in the sequence). How can we name our function? Idea: g c ? g c # T h e r e i s a l r e a d y a f u n c t i
- n
g c ( ) Another idea: g c C
- n
t e n t ? g c C
- n
t e n t N
- d
- c
u m e n t a t i
- n
f
- r
‘ g c C
- n
t e n t ’ i n s p e c i fj e d p a c k a g e s a n d l i b r a r i e s : y
- u
c
- u
l d t r y ‘ ? ? g c C
- n
t e n t ’ → We can name our function g c C
- n
t e n t ( )
5
Our function gcContent() from Day 1
Version 1 g c C
- n
t e n t <
- f
u n c t i
- n
( d n a , c
- u
n t e r = ) { d n a <
- u
n l i s t ( s t r s p l i t ( d n a , " " ) ) f
- r
( i i n 1 : l e n g t h ( d n a ) ) { i f ( d n a [ i ] = = " C " | d n a [ i ] = = " G " ) { c
- u
n t e r = c
- u
n t e r + 1 } } r e t u r n ( c
- u
n t e r / l e n g t h ( d n a ) ) } Does our function works correctly? # T e s t t h e f u n c t i
- n
w i t h s
- m
e e x a m p l e d a t a g c C
- n
t e n t ( " A A C G T G G C T A " ) g c C
- n
t e n t ( " A A T A T A T T A T " ) g c C
- n
t e n t ( 2 3 ) g c C
- n
t e n t ( T R U E ) g c C
- n
t e n t ( " n
- t
D N A " ) g c C
- n
t e n t ( " C
- l
" ) YOUR TURN
6
Dealing with problems
Problems:
- R gives an error message if the input is not a character value
- Our function calculates values if the input is most likely not a DNA