r打印频率高于一个值

时间:2014-09-15 12:47:17

标签: r printf conditional frequency

如何在表格中打印具有行/列名称的重要频率?

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

我希望看到频率为5及以上的行和列

   carb
cyl 1 2 4
  4 5 6 0
  8 0 4 6

或者,有关如何在100行和200列的频率表中查看重要数据的任何建议。

可以打印以下内容吗?

cyl  carb  count
4     1      5
4     2      5
8     4      6

2 个答案:

答案 0 :(得分:1)

你可以尝试:

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

或者

  indx <- tbl>=5
  tbl[!!rowSums(indx), !!colSums(indx)]
    carb
 #cyl 1 2 4
 #  4 5 6 0
 #  8 0 4 6

答案 1 :(得分:1)

对于第一个问题,您可以使用arr.ind的{​​{1}}参数来获取您要选择的行和列:

which

第二个问题更容易,只需强制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 data.frame

subset