1

I split a data frame based on 'index' to plot each Group side by side for comparison as:

Grp <- split(TOC, TOC$Index)

$`1`
   Site Index depth_ft TOC_mg.g IC_mg.g
1     Z     1        5       12      NA

$`1`
   Site Index depth_ft TOC_mg.g IC_mg.g
1     A     2        2       11      NA

... 
...

I can plot the data easily if I go one by one, say

plot(Grp$`1`$TOC_mg.g, Grp$`1`$depth_ft)

But when I want to plot all groups at once using 'lapply', I just see the X-Y axis without any data points in there (https://docs.google.com/file/d/0B6GUNg-8d30vdmZBMVhKVlR0TkE/edit?usp=sharing)!! Can anyone tell me what is going wrong??

#plot
par(mfrow=c(1,5))
lapply(1:length(Grp), function(i) 
  plot(Grp$`i`$TOC_mg.g, Grp$`i`$depth_ft, ylim=c(0, max(TOC$depth_ft)), 
       xlim= c(min(TOC$TOC_mg.g, na.rm=T), max(TOC$TOC_mg.g, na.rm=T)), lwd=2, col=2 ))
Metrics
  • 15,172
  • 7
  • 54
  • 83
ToNoY
  • 1,358
  • 2
  • 22
  • 43

1 Answers1

1

You should use Grp[[i]]$... rather than Grp$i$... e.g.

lapply(1:length(Grp), function(i) 
  plot(depth_ft~TOC_mg.g,data=Grp[[i]], 
       ylim=c(0, max(TOC$depth_ft)), 
       xlim= c(min(TOC$TOC_mg.g, na.rm=T), max(TOC$TOC_mg.g, na.rm=T)), 
    lwd=2, col=2 ))

There are several posts on SO about the distinction between $ and [[-indexing, but I can't find the correct incantation to search for them at the moment (searching on $ and [[ doesn't work well).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Searching for `?"[["` seems to work: e.g. http://stackoverflow.com/questions/3079415/define-right-parameter-with-a-variable-in-r/3079886#3079886 http://stackoverflow.com/questions/12574509/get-value-of-list-by-name-attribute-in-r/12574805#12574805 – Ben Bolker Aug 11 '13 at 19:13
  • Is it possible to plot more parameters (e.g. IC_mg.g) on the same plots?? Also, any way to assign different colors for each of the plots?? col=c(1:length(Grp)) doesn't work, however. – ToNoY Aug 11 '13 at 19:47
  • You should definitely look into the `lattice` or `ggplot2` packages, which can much more flexibly create multiple "faceted" subplots. If you want different colors, use e.g. `colvec=c("red","blue","orange","purple","cyan"); ... plot(...,col=colvec[i])` ... – Ben Bolker Aug 11 '13 at 21:39