Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 求矩阵中向量元素的频率_R_Matrix_Vector_Frequency - Fatal编程技术网

R 求矩阵中向量元素的频率

R 求矩阵中向量元素的频率,r,matrix,vector,frequency,R,Matrix,Vector,Frequency,我在R中有一个矩阵,下面是一个小例子: set.seed(1) n.columns<-6 mat <- matrix(, nrow = 5, ncol = n.columns) for(column in 1:n.columns){ mat[, column] <- sample(1:10,5) } mat 我还有一个整数向量v,v一个选项,使用sapply: t(sapply(v, function(a) colSums(mat==a))) # [,1] [,

我在R中有一个矩阵,下面是一个小例子:

set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat

我还有一个整数向量
v
v一个选项,使用
sapply

t(sapply(v, function(a) colSums(mat==a)))

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    0    1    0    0    1    1
#[2,]    1    0    1    1    0    1
#[3,]    0    1    1    0    1    0

使用
表格

table(mat[mat %in% v], col(mat)[mat %in% v])

#   1 2 3 4 5 6
# 1 0 1 0 0 1 1
# 3 1 0 1 1 0 1
# 6 0 1 1 0 1 0

缺点是所有值不在
v
中的列将不会报告。

在data.frame上使用
sapply

setNames(object = as.data.frame(sapply(v, function(a)
         sapply(as.data.frame(mat), function(b)
                             sum(a %in% b)))), nm = v)
#   1 3 6
#V1 0 1 0
#V2 1 0 1
#V3 0 1 1
#V4 0 1 0
#V5 1 0 1
#V6 1 1 0

当然,您可以设置行名,如
行名(res)
table(mat[mat %in% v], col(mat)[mat %in% v])

#   1 2 3 4 5 6
# 1 0 1 0 0 1 1
# 3 1 0 1 1 0 1
# 6 0 1 1 0 1 0
setNames(object = as.data.frame(sapply(v, function(a)
         sapply(as.data.frame(mat), function(b)
                             sum(a %in% b)))), nm = v)
#   1 3 6
#V1 0 1 0
#V2 1 0 1
#V3 0 1 1
#V4 0 1 0
#V5 1 0 1
#V6 1 1 0