You are here:
Vanderbilt Biostatistics Wiki
>
Main Web
>
StatComp
>
RS
>
RProgramming
(revision 2) (raw view)
Edit
Attach
%TOC% ---+ R Programming | ProgrammingTipsForStatisticians ---++ Handouts and Online Books * [[http://www.burns-stat.com/pages/Spoetry/Spoetry.pdf S Poetry]] and [[http://www.burns-stat.com/pages/Tutor/R_inferno.pdf R Inferno]] by Patrick Burns by Patrick J. Burns; a large free book on more advanced S programming in PDF format. A glossary of S and statistical terms is also available, as other links to other sites * Oxford University's [[http://www.stats.ox.ac.uk/~ruth/RCourse2/APTS.html R Programming Course]] * [[StatCompCourse][Statistical Computing Course]] * [[RClinic][R Clinic]] ---++ Common R Programming Techniques That Can Be Improved ---+++ Attaching Data Frames Attaching a data frame makes it easy to reference its variables, but if you have two data frames attached things can get confusing, and users frequently forget to detach an attached object. Better to use <tt>data=,</tt> (when calling functions that use the statistical modeling language), =with= or =within=. =within= is an alternative to =transform= and =upData=. Unlike =with=, =within= allows you to change or add variables in the referenced data frame if it was a storable object (e.g., not subscripted). <highlight> xyplot(y ~ x | g, data=mine) with(mine, { plot(x, y) plot(x, z) }) within(mine, { y <- 2*y x <- x-1 new <- x + y } </highlight> ---+++ Logical Operations R can subscript using integer vectors consisting of those subscripts meeting a certain condition, or using logical TRUE/FALSE vectors whose lengths are the lengths of the original objects tested. The latter usually leads to more readable and reliable code. Instead of <highlight> male <- which(sex=='male') al <- which(state=='AL') mean(x[intersect(male,al)]) # mean of male Alabamians </highlight> use <highlight> mean(x[sex=='male' & state=='AL']) #or: maleal <- sex=='male' & state=='AL' mean(x[maleal]) </highlight> ---+++ Repetitive Statistical Analyses Instead of <highlight> spearman2(y ~ x1 + x2, data=mydata, subset=sex=='male') spearman2(y ~ x1 + x2, data=mydata, subset=sex=='female') </highlight> consider <highlight> for(sx in levels(mydata$sex)) { cat('\n------------------------------\n', sx, '\n\n') s <- spearman2(y ~ x1 + x2, data=mydata, subset=sex==sx) print(s) } </highlight>
Edit
|
Attach
|
P
rint version
|
H
istory
:
r4
<
r3
<
r2
<
r1
|
B
acklinks
|
V
iew topic
|
Edit WikiText
|
More topic actions...
Topic revision: r2 - 30 Mar 2009,
FrankHarrell
Main
Department Home Page
Biostatistics Graduate Program
Vanderbilt University Medical Center
Main Web
Main Web Home
Search
Recent Changes
Changes
Topic list
Biostatistics Webs
Archive
Main
Sandbox
System
Register
|
Log In
Copyright © 2013-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Vanderbilt Biostatistics Wiki?
Send feedback