y <- c(1.7, "a")
class(y) [1] "character"
R has five basic or “atomic” classes of objects:
Entering 1 in R gives you a numeric object; entering 1L explicitly gives you an integer object.
Attributes of an object (if any) can be accessed using the attributes() function:
The mode() of an object tells us how it’s stored. It could happen that two different objects are stored in the same mode with different classes.
For vectors the class and mode will always be numeric, logical, or character.
For matrices and arrays a class is always a matrix or array, but its mode can be numeric, character, or logical.
The primary purpose of the class() function is to know how different functions, including generic functions, work (e.g. print, or plot). There is a collection of R commands used to assess whether a particular object belongs to a certain class, these start with is.; for example, is.numeric(), is.logical(), is.character(), is.list(), is.factor(), and is.data.frame()
This is not allowed! When different objects are mixed in a vector, coercion occurs so that every element in the vector is of the same class.
y <- c(1.7, "a")
class(y) [1] "character"
y <- c(TRUE, 2)
class(y) [1] "numeric"
y <- c("a", TRUE)
class(y) [1] "character"
Objects can be explicitly coerced from one class to another using the as. functions, if available.
x <- 0:6
class(x) [1] "integer"
as.numeric(x)[1] 0 1 2 3 4 5 6
Object names must start with a letter and can only contain letters, numbers, _, and ..
You want your object names to be descriptive, so you’ll need to adopt a convention for multiple words.
Example:
i_use_snake_case
otherPeopleUseCamelCase
some.people.use.periodsThe objects that you create using R remain in existence until you explicitly delete them or you conclude the session.
To list all currently defined objects, use ls() or objects().
To remove object x, use rm(x). To remove all currently defined objects, use rm(list = ls()).
To save all of your existing objects to a file called fname in the current working directory, use save.image(file = "fname").
To save specific objects (say x and y) use save(x, y, file = "fname").
To load a set of saved objects use load(file = "fname").
To save this history to the file fname use savehistory(file = "fname") and to load the history file fname use loadhistory(file = "fname").
In R an expression is used to denote a phrase of code that can be executed.
Example:
## An expression
seq(10, 20, 3)The combination of expressions that are saved for evaluation is called an assignment:
## An assignment
object_name <- valueWhen reading that code, say “object name gets value” in your head. You will make lots of assignments, and <- is a pain to type.
You can save time with RStudio’s keyboard shortcut: Alt + - (the minus sign).