Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
当缺少因子水平时,您可以通过以下方式使用表:
marks <- c(1,5,3,4,5,6) table(ordered(marks,levels=1:6))
这将返回一个以零频率列出的级别为“2”的表。
如果有一组与“分数”相关联的“分数”并且没有缺失的级别(这里是 2),tapply则可以用于生成每个级别的分数总和。
tapply
tapply(scores,marks,sum)
tapply 可以适应“缺失”因子水平的情况吗?或者,还有更好的方法?
这里的想法是模拟 表函数行为。
首先,我生成一个分数向量,分数 <- 样本(1:6)
然后分两步:
tapply 以获取未命中值的 NA 分数。在这里,我使用 sum 函数,如 table 函数,但我们可以使用任何自定义函数(max、min、..)
res <- tapply( scores , ordered(marks,levels=1:6),function(x) {sum(x)} )
然后只需替换缺失值
res[is.na(res)] <- 0