-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathR02_basics.qmd
91 lines (63 loc) · 1.75 KB
/
R02_basics.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# Variables, Values, Functions
## Variables
* assign values to variables either with `<-` or `=`
* variable on the left, assigned value on the right
* You decide how to name a variable.
* Use recognizable names!
* Don't be lazy. Longer, descriptive names help immensely.
```{r}
a <- 5
b = 10
a_big_number = 500000
```
## Values
* values are the "things" you store in variables
* e.g. numbers or text
* values belong to a `class`
* common classes:
* `numeric`: numbers
* `character`: text / string
* `logical`: TRUE or FALSE
```{r, eval = FALSE}
# numeric
1
68542
4.5
# character
"f"
"Hi Mom!"
# logical
TRUE
FALSE
```
## Functions
* Functions do something with values or variables.
* Everything you do in R is a function.
* Easily identified by function name followed by parenthesis (), e.g. `print()`
* for common functions there are shortcuts (e.g. `+` or `<-`)
```{r}
# the class() function returns the type of the input
a <- 5
class(a)
# the nchar() function returns the number of characters in a string
nchar("Hi Mom")
# <- is a shortcut for the `assign` function
assign("a", 5)
print(a)
`<-`(b, 10)
print(b)
d <- 11
print(d)
```
* most functions need __arguments__
* input, options or parameters to specify what the function should do
* each function has a help page where you can read about arguments
For example, the `cos()` function computes the cosine of a number. The help page specifies what the function expects as an input. You can access the help page with `?cos()` or by searching for the function in the 'Help' tab in Rstudio (bottom right panel).
```{r, error = TRUE}
# the cos function needs the argument x of type numeric
cos(x = 0)
# it throws an error otherwise
cos(x = "3.14")
# argument names can be neglected
cos(1)
```