R for Marketing Research and Analytics

Chris Chapman and Elea McDonnell Feit
January 2016

Chapter 2: Basics of the R Language

Website for all data files:
http://r-marketing.r-forge.r-project.org/data.html

Objects

\rightarrow We'll cover some of the basic object types in R

\rightarrow Objects in R include variables, data sets, and functions

Basic objects

The assignment operator <- assigns a value to a named object.

x <- c(2, 4, 6, 8)
x
[1] 2 4 6 8

Object names are case sensitive. Instead of 'x', 'X' produces an error:

X
Error in eval(expr, envir, enclos): object 'X' not found

Vectors

We've just seen how to create a vector: the c() function concatenates individual items into a vector.

xNum  <- c(1, 3.14159, 5, 7)
xNum
[1] 1.00000 3.14159 5.00000 7.00000
xLog  <- c(TRUE, FALSE, TRUE, TRUE)
xLog
[1]  TRUE FALSE  TRUE  TRUE
xChar <- c("foo", "bar", "boo", "far")
xChar
[1] "foo" "bar" "boo" "far"

Saving images (but generally, don't!)

Save to “.Rdata”:

  • save.image()

Save to arbitrary filename

  • save.image(“mywork.RData”)

Load an image

  • load(“mywork.RData”)

That's all for Chapter 2!

Break time

Notes

This presentation is based on Chapter 6 of Chapman and Feit, R for Marketing Research and Analytics © 2015 Springer. http://r-marketing.r-forge.r-project.org/

Exercises here use the Salaries data set from the car package, John Fox and Sanford Weisberg (2011). An R Companion to Applied Regression, Second Edition. Thousand Oaks CA: Sage. http://socserv.socsci.mcmaster.ca/jfox/Books/Companion

All code in the presentation is licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.