Miscellaneous R notes

© 2005 Ben Bolker

  1. installing packages without administrative privileges: The following commands install R packages (in this case the plotrix, gplots, gtools and gdata packages) into a working folder and then attach them. First go to the file menu, and Change dir to your Desktop or My Documents or something. Then:
    > desktop = getwd()
    > options(repos = "http://cran.us.r-project.org")
    > install.packages("plotrix", destdir = desktop, lib = desktop)
    > library(plotrix, lib = desktop)
    > install.packages("gplots", destdir = desktop, lib = desktop)
    > install.packages("gtools", destdir = desktop, lib = desktop)
    > install.packages("gdata", destdir = desktop, lib = desktop)
    > library(gtools, lib = desktop)
    > library(gdata, lib = desktop)
    > library(gplots, lib = desktop)
     
    
  2. Dealing with times in R (lab 2): use the times() function in the chron library to convert character vectors or factor to times. e.g.:
    > timevec1 = c("11:00:00", "11:25:30", "15:30:20")
    > times1 = times(timevec1)
     
    
    If you have times with no seconds component, use something like timevec1=paste(timevec1,":00",sep="") to add seconds before you try to convert.
  3. More on reshaping data:
    > set.seed(1001)
    > mydata = data.frame(indiv = rep(1:3, c(3, 4, 5)), sex = factor(c(rep("F", 
    +     7), rep("M", 5))), day = c(1:3, 1:4, 1:5), dist = runif(12))
     
    
    Reshaping data (as Caro says) introduces NA values:
    > r1 = reshape(mydata, direction = "wide", idvar = "indiv", timevar = "day", 
    +     v.names = "dist")
    > r1
     
    
      indiv sex     dist.1    dist.2    dist.3      dist.4    dist.5
    1     1   F 0.98568878 0.4126285 0.4295392          NA        NA
    4     2   F 0.41917224 0.4265066 0.8877976 0.006096034        NA
    8     3   M 0.08121576 0.2886574 0.7653421 0.442924182 0.1383630
    
     
    
    Tabulate number of individual females in this format:
    > table(r1$sex)
     
    
    
    F M 
    2 1 
    
     
    
    There may be a better way to do this but I haven't thought of it yet ...
    > splitdata = split.data.frame(mydata, mydata$indiv)
    > firstlines = lapply(splitdata, function(x) x[1, ])
    > recombined = do.call("rbind", firstlines)
     
    



File translated from TEX by TTH, version 3.67.
On 15 Sep 2005, 14:01.