列表中的堆积条形图

Stacked Bar Chart from List

我有以下矩阵

  IdCarrefour 10 11 12 13
1           2  3  8  5 NA
2           4 NA  4  1 NA
3           5 NA NA NA NA
4           6 NA  4  1 NA
5           7 NA NA NA NA

对于每个列,我想知道我得到了多少个 NA 和多少个非 NA。所以我使用了apply函数:

mTF<-apply(m,2,function(x) table(!is.na(x)))
> str(mTF)
List of 5
 $ IdCarrefour: 'table' int [1(1d)] 5
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr "TRUE"
 $ 10         : 'table' int [1:2(1d)] 4 1
  ..- attr(*, "dimnames")=List of 1
  .. ..$ : chr [1:2] "FALSE" "TRUE"

其中 mTF 是一个列表。现在我想使用 ggplot 绘制堆积条形图。

所以我尝试将 mTF 转换为 data.frame。在其他相关帖子的帮助下,我想出了这两种方法:

data.frame(matrix(unlist(mTF), nrow=5, byrow=T),stringsAsFactors=FALSE)
Warning message:
In matrix(unlist(mTF), nrow = 5, byrow = T) :
  data length [8] is not a sub-multiple or multiple of the number of rows [5]

不适合我,因为我对每个级别没有相同的因素(见警告)

do.call(rbind.data.frame, mTF)

也不起作用,因为它复制了缺失的级别(对于最后一行,我应该有 0 T 和 5 F)。

            c.5L..4L..2L..2L..5L. c.5L..1L..3L..3L..5L.
IdCarrefour                     5                     5
10                              4                     1
11                              2                     3
12                              2                     3
13                              5                     5

那么有没有办法将我的列表 (mTF) 转换成我可以用来绘图的 data.frame?

首先我们需要对您的数据进行一些操作。请注意,我已将您的矩阵转换为名为 df:

data.frame
df

  IdCarrefour X10 X11 X12 X13
1           2   3   8   5  NA
2           4  NA   4   1  NA
3           5  NA  NA  NA  NA
4           6  NA   4   1  NA
5           7  NA  NA  NA  NA
#create new data.frame
df2 <- rbind(
            stack(apply(df, 2, FUN = function(x) sum(is.na(x)))), #NA
            stack(apply(df, 2, FUN = function(x) sum(!is.na(x)))) #not NA
            )
df2

   values         ind
1       0 IdCarrefour
2       4         X10
3       2         X11
4       2         X12
5       5         X13
6       5 IdCarrefour
7       1         X10
8       3         X11
9       3         X12
10      0         X13
#add indicator column
df2 <- data.frame(df2, Indicator = rep(c('NA','Not NA'), each = 5))
#remove IdCarrefour
df2 <- subset(df2, ind != 'IdCarrefour')
#make plot
ggplot(df2, aes(x = ind, y = values))+geom_bar(stat = 'identity', aes(fill = Indicator))