How do I print the significant frequencies in a table, with row / column names?
with(mtcars,table(cyl,carb))
carb
cyl 1 2 3 4 6 8
4 5 6 0 0 0 0
6 2 0 0 4 1 0
8 0 4 3 6 0 1
I'd like to see the rows and columns for frequencies 5 and above
carb
cyl 1 2 4
4 5 6 0
8 0 4 6
Or, any suggestions on how to see the significant data in a frequency table with 100 rows and 200 columns.
Can the following be printed?
cyl carb count
4 1 5
4 2 5
8 4 6
You could try:
tbl <- with(mtcars, table(cyl, carb))
dat1 <- subset(as.data.frame(with(mtcars,table(cyl,carb))), Freq>=5)
tbl2 <- xtabs(Freq~., droplevels(dat1))
indx <- match(outer(rownames(tbl2), colnames(tbl2), FUN=paste0),outer(rownames(tbl), colnames(tbl), FUN=paste0))
tbl2[] <- tbl[indx]
tbl2
# carb
#cyl 1 2 4
# 4 5 6 0
# 8 0 4 6
Or
indx <- tbl>=5
tbl[!!rowSums(indx), !!colSums(indx)]
carb
#cyl 1 2 4
# 4 5 6 0
# 8 0 4 6
For your first question, you can use the arr.ind
argument of which
to get the rows and columns that you wish to select:
x <- with(mtcars,table(cyl,carb))
inds <- which(x>=5,arr.ind=TRUE)
x[unique(inds[,"row"]),unique(inds[,"col"])]
carb
cyl 1 2 4
4 5 6 0
8 0 4 6
The second question is easier, just coerce to data.frame
and subset
:
subset(as.data.frame(x),Freq>=5)
cyl carb Freq
1 4 1 5
4 4 2 6
12 8 4 6
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.