March, 2010


25
Mar 10

R plotting fun

Not easy to produce cool looking graphs in R, but it can be done. The results of some messing around are above. Here is the code I used:

x = runif(1000)
y = x/runif(1000)

cexes = 10*y/max(y) # For circle size
par(bg="black") # I see a white background and I want it painted black.
par(mar=c(0,0,0,0)) # Margins? We don't kneed no stinkin' margins.
plot(x,log(y), pch=20, col="white", cex=cexes) 

21
Mar 10

R: Add vertical line to a plot

If you have a plot open and want to add a vertical line to it:

abline(v=20) #Add vertical line at x=20

21
Mar 10

R: Geometric mean

gm(x) 

But this requires package heR.Misc so you might as well just use:

exp(mean(log(x)))

20
Mar 10

R: remove all objects fromt he current workspace


20
Mar 10

R: Backwards for loop

 
for (i in 10:1) {
	print(i)
}

As easy as that.


18
Mar 10

R: Count unique items in a vector

Had to look this one up, so here it is:

length(unique(x))

Counts the number of distinct items in a vector in R.


17
Mar 10

Useful R link

Questions at stackoverflow about R:


17
Mar 10

R: “while” loops

R has regular while loops:

while (condition) {

Note that if you try to get help about while you get an error:

help(while)

Error: unexpected ‘)’ in “help(while)”


16
Mar 10

>An error I got

>

Error in -value : invalid argument to unary operator

The problem was that I had the following code

fcnName <<-- value

Check out the extra dash typo, since R gives you no line numbers with the errors it took me a bit to track this down. Note the double << makes the assignment global in scope.


16
Mar 10

R tip iterating over list

To iterate over a list by key, value pair, do this:

for (name in names(myList)) {
    print(name)
print(myList[[name]])
}

Note the double [[]] so you get just the value, not the pair.