r - Data frame of tables from a list -
r - Data frame of tables from a list -
suppose have list observations:
foo <- list(c("c", "e", "a", "f"), c("b", "d", "b", "a", "c"), c("b", "c", "c", "f", "a", "f"), c("d", "a", "a", "d", "d", "f", "b" )) > foo [[1]] [1] "c" "e" "a" "f" [[2]] [1] "b" "d" "b" "a" "c" [[3]] [1] "b" "c" "c" "f" "a" "f" [[4]] [1] "d" "a" "a" "d" "d" "f" "b" and vector each unique element:
vec <- letters[1:6] > vec [1] "a" "b" "c" "d" "e" "f" i want obtain info frame counts of each element of vec in each element of foo. can plyr in ugly unvectorized way:
> ldply(foo,function(x)sapply(vec,function(y)sum(y==x))) b c d e f 1 1 0 1 0 1 1 2 1 2 1 1 0 0 3 1 1 2 0 0 2 4 2 1 0 3 0 1 but that's slow. how can done faster? know of table() haven't figured out how utilize due 0-counts in of elements of foo.
one solution (off top of head):
# convert foo list of factors lfoo <- lapply(foo, factor, levels=letters[1:6]) # apply table() each list element t(sapply(lfoo, table)) b c d e f [1,] 1 0 1 0 1 1 [2,] 1 2 1 1 0 0 [3,] 1 1 2 0 0 2 [4,] 2 1 0 3 0 1 r table
Comments
Post a Comment