<- 5
a = 10
b
= 500000 a_big_number
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.
Values
- values are the “things” you store in variables
- e.g. numbers or text
- values belong to a
class
- common classes:
numeric
: numberscharacter
: text / stringlogical
: TRUE or 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<-
)
# the class() function returns the type of the input
<- 5
a class(a)
[1] "numeric"
# the nchar() function returns the number of characters in a string
nchar("Hi Mom")
[1] 6
# <- is a shortcut for the `assign` function
assign("a", 5)
print(a)
[1] 5
`<-`(b, 10)
print(b)
[1] 10
<- 11
d print(d)
[1] 11
- 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).
# the cos function needs the argument x of type numeric
cos(x = 0)
[1] 1
# it throws an error otherwise
cos(x = "3.14")
Error in cos(x = "3.14"): non-numeric argument to mathematical function
# argument names can be neglected
cos(1)
[1] 0.5403023