【问题标题】:Finding the number of each factor per column in R查找R中每列每个因子的数量
【发布时间】:2012-12-27 16:41:47
【问题描述】:

我正在尝试编写代码,允许我在 R 中找到每列每个因子的数量,但我希望每列中的因子水平相同。我认为这应该是微不足道的,但我遇到了两个地方,当使用 apply with factor 和使用 apply with table 时,R 没有返回我期望的值。

考虑这个样本数据:

mat <- matrix(sample(1:10,90,replace=TRUE),ncol=10,nrow=9)
mat.levels <- as.character(unique(as.vector(mat)))
mat.factor <- as.data.frame(apply(mat,2,as.character))

我的第一步是重新调整每一列的水平,以使因子水平相同。一开始我试过:

apply(mat.factor,2,factor,levels=mat.levels)
#But the data structure is all wrong, I don't appear to have a factor anymore!
str(apply(mat.factor,2,factor,levels=mat.levels))

所以我使用循环来强制它......

for (i in 1:ncol(mat.factor)) {
      levels(mat.factor[,i]) <- mat.levels
    }

然后我遇到了另一个应用问题。我认为现在我已经设置了因子水平,如果我在列中缺少给定因子,则表函数应该为该因子水平返回 0 计数。但是,当我使用 apply 时,似乎删除了计数为零的因子水平!

apply(mat.factor,2,table)$V10
str(apply(mat.factor,2,table)$V10)
#But running table just on that one column yields the expected result!
table(mat.factor[,10])
str(table(mat.factor[,10]))

有人能解释一下这两种情况发生了什么吗?我在误解什么?

【问题讨论】:

    标签: r matrix apply r-factor


    【解决方案1】:

    阅读?apply的Details部分的第一句,然后运行as.matrix(mat.factor)查看问题。对数据帧使用lapply,而不是apply

    这是一个例子:

    mat.factor <- as.data.frame(lapply(mat.factor,factor,levels = mat.levels))
    lapply(mat.factor,table)
    

    【讨论】:

    • 糟糕,这很明显。我陷入了 data.frame 的矩阵式结构中,忘记了它是一种列表。
    • @drknexus 你有很多人会犯这个错误。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2020-08-21
    • 2021-05-22
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多