Montag, 19. September 2011

Mengen-Vergleiche

Interessanten Mengenvergleichs-Funktionen:

(A <- c(sort(sample(1:20, 9)),NA))

[1] 1 2 3 12 16 17 18 19 20 NA
(B <- c(sort(sample(3:23, 7)),NA))
[1] 8 10 15 16 18 21 22 NA


# alle Elemente aus A und B (KEINE Duplikate)
union(A, B)
[1] 1 2 3 12 16 17 18 19 20 NA 8 10 15 21 22

# alle Elemente die in A und in B vorkommen (Schnittmenge)
intersect(A, B)
[1] 16 18 NA

# Elemente in A, aber nicht in B vorkommen
setdiff(A, B)
[1] 1 2 3 12 17 19 20

# Elemente in B, aber nicht in A vorkommen
setdiff(B, A)
[1] 8 10 15 21 22


# Enthält A die gleichen Elemente wie B?
setequal(A, B)
[1] FALSE

Donnerstag, 15. September 2011

Function call with a list of arguments

Use do.call to call a function with a previously built list of arguments:

# Define the arguments

args.legend <- list(
  x = "topleft"
  , legend = c(1,2)
  , fill = c("red","blue")
  , xjust = 1, yjust = 1)

plot(1:10, 1:10)
# call function with the arguments' list
do.call("legend", args.legend)

Get information about invisible built-in functions

How can we see the code of invisible functions, i.e. mosaicplot? 

> mosaicplot

yields only:

function (x, ...)
UseMethod("mosaicplot")


but the functions "methods" and "getAnywhere" do the trick:

> methods(mosaicplot)

[1] mosaicplot.default* mosaicplot.formula*

Non-visible functions are asterisked

> getAnywhere("mosaicplot.formula")
A single object matching ‘mosaicplot.formula’ was found
It was found in the following places
registered S3 method for mosaicplot from namespace graphics
namespace:graphics
with value

function (formula, data = NULL, ..., main = deparse(substitute(data)),
subset, na.action = stats::na.omit)
{
main
m <- match.call(expand.dots = FALSE)
.....

Donnerstag, 8. September 2011

Layout-Muster

Split screens:

m <- matrix(0:3, 2, 2)
layout(m, c(1, 3), c(1, 3))
layout.show(3)


m <- matrix(1:4, 2, 2)
layout(m, widths=c(1, 3), heights=c(3, 1))
layout.show(4)

Date formats and functions

Date formats:


Remember the functions:

d <- as.Date(c("1937-01-10","1916-03-02","1913-09-19","1927-12-23","1947-07-28"))

quarters(d)
[1] "Q1" "Q1" "Q3" "Q4" "Q3"


# ... or as function
quarter <- function (x) {
  # Berechnet das Quartal eines Datums
  y <- as.numeric( format( x, "%Y") )
  paste(y, "Q", (as.POSIXlt(x)$mon)%/%3 + 1, sep = "")
}

# ... or alternatively with cut
cut(d, breaks="quarters")
[1] 1937-01-01 1916-01-01 1913-07-01 1927-10-01 1947-07-01
137 Levels: 1913-07-01 1913-10-01 1914-01-01 1914-04-01 ... 1947-07-01


months(d)
[1] "Januar" "März" "September" "Dezember" "Juli"

format(d,"%B") # months alternative
[1] "Januar" "März" "September" "Dezember" "Juli"

format(d,"%Y") # years
[1] "1937" "1916" "1913" "1927" "1947"