Skip to content

Instantly share code, notes, and snippets.

@patperu
Created July 12, 2011 15:24
Show Gist options
  • Save patperu/1078191 to your computer and use it in GitHub Desktop.
Save patperu/1078191 to your computer and use it in GitHub Desktop.
Verteilung von Konten
#
# Korrektur 13.07.2011
# - In 'fracbelow' = sort muss "decreasing = TRUE"
#
library(reshape) # für melt
library(ggplot2) # für plot
# Zufallsgenerator setzen
set.seed(123)
# Beispieldaten generieren
# - Kontostand zwischen 0 und 100
# - 100 Personen mit je 20 Konten (n = 2000)
x <- sample(0:100, 2000, replace=TRUE)
# 25% der 2000 Konten auf NA setzen, d.h. diese Person nutzt dieses
# Konto nicht
x1 <- sample(1:2000, 500, replace=TRUE)
x[x1] <- NA
# Vector zu Matrix
x <- matrix(x, nrow=100)
# Wie viele Konten nutzt die jeweilige Person
n.notempty <- apply(x, 1, FUN=function(x) sum(!is.na(x)))
# Verteilung der Kontonutzung
# 1 Person nutzt 10 Konten, 4 Personen nutzen 19 Konten
table(n.notempty)
# Matrix zu data.frame, in der ersten Spalte steht die Personen-ID.
# 100 Personen mit max. 20 Konten
w <- data.frame(personid = 1:nrow(x), x)
# Von wide in long format (analog zu VARSTOCASES bei SPSS)
wm <- melt(w, id.vars = "personid")
# prop.table - Verteilung auf die Konten
# cumsum - kummulierte Anteil je Person
# xcut - hier 0.8-Grenze
# na.omit - ohne fehlende Werte = ohne die ungenutzten Konten
# n = Anzahl der Konten
# -> Anmerkung: n kann auch nur bspw. 73% abdecken, wenn
# das Guthaben auf dem nächsten Konto kummuliert
# über 80% ergäbe.
# cumAnteil - %-Anteil des Vermögens, das auf den n-Konten liegt
fracbelow <- function(x, xcut) {
u <- prop.table(na.omit(x))
u <- sort(u, decreasing = TRUE)
n <- sum(cumsum(u) <= xcut)
cumAnteil <- round(cumsum(u)[[n]], 2)
out <- data.frame(n, cumAnteil)
return(out)
}
# Berechne für jede Person die Anzahl der Konten, auf denen
# kleiner gleich 80 Prozent des "Vermögens" liegen sowie den
# tatsächlichen Anteil (cumAnteil).
wm.e <- lapply(split(wm$value, wm$personid),
FUN=function(x) fracbelow(x, 0.8))
wm.e <- do.call("rbind", wm.e)
# Zusammenfassen
z <- data.frame(w, wm.e, n.notempty)
# Verteilung der Konten der 100 Personen
# Bei 2 Personen verteilen sich 74% bzw. 77% des Vermögens
# auf 5 Konten
addmargins(table(z$cumAnteil, z$n))
# Fluctuation diagram, see:
# http://had.co.nz/ggplot/plot-templates.html#fluctuation
ggfluctuation(table(z$cumAnteil, z$n), type="colour")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment