I need to find frequency of numbers say 0:8. in an every column of matrix A of order mxn.
How can I do that?
thanks in advance
You can use apply
with MARGIN=2
to loop through the columns, subset the elements that are 0:8 ( x %in% 0:8
), convert to factor
with levels
specified as 0:8
and use table
to get the frequency of elements.
apply(A, 2, function(x) table(factor(x[x %in% 0:8], levels=0:8)))
Or another option would be to melt
the matrix and convert to data.table
using setDT
, subset 0:8 ( J(0:8)
) from the "value" column after the setting the "value" column as key ( setkey
), group by "Var2", change the "value" column to "factor" class and get the frequency with table
library(data.table)
setkey(setDT(melt(A)), value)[J(0:8),
as.list(table(factor(value, levels=0:8))), by= Var2]
set.seed(24)
A <- matrix(sample(0:15, 10*20, replace=TRUE), ncol=10)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.