apply

Learning by examples:

squares, in matrix form, wide

sapply(1:14, function (x) {
  a <- x
  b <- x * x
  c(a,b)
 }
)

squares, in matrix form, tall

matrix(sapply(1:14, function (x) {
   a <- x
   b <- x * x
   c(a,b)
  }
 ),
ncol=2, byrow=T)

squares, in list form

sapply(1:14, function (x) {
  a <- x
  b <- x * x
  c(a,b)
 }, simplify = F
)

accessing more than one element at a time from a list

Consider a list of two vectors, one numerical vector holding a code and a vector of characters holding a name:

str(tingsrätter)
List of 2
 $ kod : num [1:12] 448 449 457 263 264 265 450 451 453 458 ...
 $ namn: chr [1:12] "Göteborg" "Mölndal" "Alingsås" "Lidköping" ...

Suppose you want to construct a string by combining the name with the code, e.g. for use in a filename.

unlist(lapply(tingsrätter$namn, function (x) (paste(x, "-", tingsrätter$kod[tingsrätter$namn == x], ".txt", sep = ""))))

Or you could do it in a more for-loop-like way

unlist(lapply(1:length(tingsrätter$namn), function (x) (paste(tingsrätter$namn[x], "-", tingsrätter$kod[x], ".txt", sep = ""))))

get row.profiles or column profiles in percentages E.g this frequency table

table(eld,aktfast)
                  aktfast
eld                    ingen gång     1 gång 2 ggr 3 ggr eller fler
  Ingen gång             6186    627    93               64
  1-2 ggr                 169     51    23               22
  3-5 ggr                  18      9     6               10
  6-10 ggr                  8      6     2                7
  11-50 ggr                 7      2     2                4
  Mer än 50 ggr             6      3     1                2
my.prop.table.by.column("eld", "aktfast", ar.2005)
                       ingen gång     1 gång 2 ggr 3 ggr eller fler
  Ingen gång               97     90    73               59
  1-2 ggr                   3      7    18               20
  3-5 ggr                   0      1     5                9
  6-10 ggr                  0      1     2                6
  11-50 ggr                 0      0     2                4
  Mer än 50 ggr             0      0     1                2

my.prop.table <- function (row = "foo", column = "bar", dataframe = data.frame, by = "row") {
  a <- prop.table(table(dataframe[[row]], dataframe[[column]]))
  index <- 2
  n <- nrow(a)
  byrow = F
  if (by == "row") {
    index <- 1
    n <- ncol(a)
    byrow = T
  }
  b <- apply(a, index, sum)
  round(100*(a/matrix(unlist(sapply(b, function (x) (rep(x, n)))), ncol=ncol(a), byrow = byrow)))
}

comments powered by Disqus


Back to the index

Blog roll

R-bloggers, Debian Weekly
Valid XHTML 1.0 Strict [Valid RSS] Valid CSS! Emacs Muse Last modified: oktober 17, 2019