Skip to Main Content
Go to Penn Libraries homepage   Go to Guides homepage

R for Business Guide

Quick start

Common object types in R include

  • Vector
    c(value, value, ...)
  • Data frame
    data.frame(col_name = value, col_name = value, ...)

Vector

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

Data frame

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

Business & Data Analysis Librarian

Profile Photo
Kevin Thomas
He/Him/His
Subjects: Statistics

Chat

Penn Libraries Home Search the Catalog
(215) 898-7555