Common object types in R include
c(value, value, ...)
data.frame(col_name = value, col_name = value, ...)
In R, a vector refers to values of the same type (e.g.: numeric; character) stored in an ordered sequence.
Use the c
function to combine values into a vector, e.g.:
c(2, 4, 16)
c('a', 'b', 'c')
vec <- c(1:5)
To retrieve values from a vector, refer to the position(s) of the value(s) you want, e.g.:
vec # the entire vector vec
vec[1] # the first value in the vector vec
vec[2:4] # the second through fourth values in the vector vec
vec[c(1, 4)] # the first and fourth values in the vector vec
vec[-1] # every value except the first value in the vector vec
A data frame stores data in a tabular format. Each column or field is a vector, typically with a name. From one vector to the next, data types can be different. Each vector in a single data frame must have the same length.
Use the data.frame
function to create a data frame, e.g.:
df <- data.frame(Firm = c('Lockheed Martin', 'Airbus', 'Boeing'),
Rank = c(1:3))
You can retrieve values from a data frame by referring to their position(s) in matrix notation, e.g.:
df # the entire data frame df
df[2, 1] # the value in row two, column one of df
df[2, ] # the entire row two of df
df[ , 1] # the entire column one of df
df[1:2, c("Firm")] # the values in rows one through two of the column named Firm in df
Or retrieve vectors by name, e.g.:
df$Firm # the entire column named Firm in df
df$Firm[2] # the second value of the column named Firm in df