1 of 15

Manipulating Data

Johns Hopkins Bloomberg School of Public Health

Instructor: Jeff Leek

Youtube: http://www.youtube.com/JHSPHAppliedStat

2 of 15

Here is what data looks like in classes

3 of 15

Here is what data looks like in real life

4 of 15

Here is what data looks like in real life

 

5 of 15

Here is what data looks like in real life

view-source:http://espn.go.com/nba/standings

6 of 15

Data may also be in other formats

7 of 15

What do we want at the end?

"Tidy Data"

  • One variable per column
  • Column names are variable names
  • Variables in only columns (rows)
  • Sensible coding of variables
  • Variable names matched across files

8 of 15

[,]

  • Most useful feature of R?

9 of 15

which()

  • Identifies elements of a matrix/vector
  • Important parameters
    • arr.ind 

10 of 15

merge()

  • merges data sets based on common columns
  • Important parameters
    • by, all.x, all.y 

11 of 15

%in%

  • a %in% b matches elements of a to b
  • match() is the more complete interface

12 of 15

Set operations

  • union(x,y)
  • intersect(x,y)
  • setdiff(x,y)
  • setequal(x,y)

13 of 15

tapply()

  • Applies a function to groups of variables
  • Better than the equivalent for loop
  • See also by()
  • Important parameters
    • x, index, fun,simplify

14 of 15

lapply()

  • Applies a function to elements of a list
  • Important parameters
    • x, fun 

15 of 15

sapply()

  • User friendly wrapper for lapply()
  • sapply(x,f,simplify=FALSE,use.names=FALSE)

= lapply(x,f)