december 2015


Last week

  • How to assign elements to objects (<-)
  • How to run code
  • How to save R-scripts
  • How to create vector, matrix, dataframe, and list objects
  • How to obtain specific elements, rows, or columns from those objects (objectname[2,4])
  • How to use functions


Today: Analyzing data

  • How to import your data into R
  • How install and load packages
  • Recoding items and calculating sumscores
  • Regression analysis
  • SEM with package lavaan
  • multilevel modeling with package lme4

Reading help files.

A bit more about environments

Environments in R

There are several 'layers' in R. For example:

  • The global environment
  • environments in functions
  • Packages
  • There is more, but that is beyond the scope of this course :)


  • If you create a function, it is positioned in the global environment.

  • Everything that happens in a function, stays in a function. Unless you specifically tell the function to share the information with the global environment.


  • Packages have their own space.

  • this is important, because different packages may have functions with the same name.

  • for example, summary() is a function in both package lavaan and package lme4.

  • If you load package lavaan, and then package lme4, the summary function will refer to the one in package lme4.

  • but you can use both by using: lavaan::summary() and lme4::summary()

Saving and loading things in R

  • you already know how to save your scripts.

Saving your workspace

A workspace contains all changes you made to environments.

You can save a workspace and continue exactly where you left.

Workspaces are compressed and require relatively little memory when stored.

Saving your history

R by default saves (part of) the code history. (Use up arrow key in the console)

  • savehistory(file = "Stuff.Rhistory")
  • loadhistrory(file = "Stuff.Rhistory")

Saving and loading specific objects from R

  • You can save specific objects in an .Rdata file with function save().
  • You can load .Rdata files with function load()

  • save(object1,object2,object3, file = "savedobjects.Rdata")
  • load(file="savedobjects.Rdata")

Saving and loading .txt, .csv or .dat files (table format files)

  • You can save an object in an .cvs, .txt or .dat file with function write.table().
  • You can load such files with function read.table()

  • write.table(object1, file = "savedobject.csv", sep=";", col.names = TRUE, row.names=FALSE)
  • read.table(file="savedobject.csv", sep=";", header=TRUE)

Installing and Loading packages in R

Packages in R

Packages in R