4

我想通过它们的列找到矩阵的频率。例如对于下面的矩阵 x

   x <- matrix(c(rep(1:4,3),rep(2:5,2)),4,5)
   x
         [,1] [,2] [,3] [,4] [,5]
   [1,]    1    1    1    2    2
   [2,]    2    2    2    3    3
   [3,]    3    3    3    4    4
   [4,]    4    4    4    5    5

现在如何找到每个唯一列的频率并创建一个矩阵,每列是 x 的唯一列,最后一行作为它在矩阵 x 中的频率添加

 #freqmatrix
        [,1] [,2]
 [,1]      1  2
 [,2]      2  3
 [,3]      3  4
 [,4]      4  5
 [,5]      3  2
4

4 回答 4

5

这是一个避免将矩阵转换为列表列表的解决方案,但它也有点混乱:

x.unique <- unique(x, MARGIN  = 2)

freq <- apply(x.unique, MARGIN = 2, 
              function(b) sum(apply(x, MARGIN = 2, function(a) all(a == b)))
        )

rbind(x.unique, freq)

     [,1] [,2]
        1    2
        2    3
        3    4
        4    5
freq    3    2
于 2013-01-21T09:12:57.070 回答
3

你的最终目标到底是什么?换句话说,您将如何进一步处理这些数据?如果它只是制表,不会paste()让你得到答案吗?

x <- matrix(c(rep(1:4,3),rep(2:5,2)),4,5)
x1 <- data.frame(table(apply(x, 2, paste, collapse = ", ")))
#         Var1 Freq
# 1 1, 2, 3, 4    3
# 2 2, 3, 4, 5    2

如果您确实想要Var1分离,您可以read.csv()在该列上使用。

cbind(read.csv(text = as.character(x1$Var1), header = FALSE), x1[-1])
#   V1 V2 V3 V4 Freq
# 1  1  2  3  4    3
# 2  2  3  4  5    2

或者,如果您更喜欢转置输出:

t(cbind(read.csv(text = as.character(x1$Var1), header = FALSE), x1[-1]))
#      [,1] [,2]
# V1      1    2
# V2      2    3
# V3      3    4
# V4      4    5
# Freq    3    2
于 2013-01-21T15:49:20.490 回答
2

这个答案会有点混乱,因为它涉及我无法避免的列表列表:

x <- matrix(c(rep(1:4,3),rep(2:5,2)),4,5)
#convert columns to elements in list
y <- apply(x, 2, list)

#Get unique columns
unique_y <- unique(unlist(y, recursive=FALSE))

#Get column frequencies
frequencies <- sapply(unique(y), function(f) sum(unlist(y, recursive=FALSE) %in% f))

#Bind unique columns with frequencies
rbind(simplify2array(unique_y), frequencies)

瞧:

            [,1] [,2]
               1    2
               2    3
               3    4
               4    5
frequencies    3    2
于 2013-01-21T08:45:13.780 回答
2

一个班轮使用aggregate(如果您的输入是 a data.frame):

y <- matrix(c(1:4, 2:5, 1:4, 1,3,4,5, 2:5), ncol=5)
> y
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    1    1    2
# [2,]    2    3    2    3    3
# [3,]    3    4    3    4    4
# [4,]    4    5    4    5    5

z <- as.data.frame(t(y))
> t(aggregate(z, by=z, length)[1:(ncol(z)+1)])
#      [,1] [,2] [,3]
# V1      1    1    2
# V2      2    3    3
# V3      3    4    4
# V4      4    5    5
# V1.1    2    1    2

注意:如果输入矩阵中的列数x大于其 nrows,即ncol(x) >> nrow(x).

于 2013-01-21T10:20:03.830 回答