new.id
new.card_number
new.card_holdername
让我们考虑一下,我已经生成了一个上面的矩阵。我想将上述矩阵中的特定字符(例如:“ B”)的数量存储到单独的向量中。
我期望这样的结果:
> f
[,1] [,2] [,3]
[1,] "A" "B" "A"
[2,] "B" "B" "B"
[3,] "B" "B" "C"
f_B是另一个向量
答案 0 :(得分:2)
我们可以在逻辑colSums
上使用matrix
f_B <- colSums(f == "B")
f_B
#[1] 2 3 1
如果我们需要获取每一列的每个唯一元素的频率
table(f, col(f))
#f 1 2 3
# A 1 0 1
# B 2 3 1
# C 0 0 1
f <- structure(c("A", "B", "B", "B", "B", "B", "A", "B", "C"),
.Dim = c(3L, 3L))
答案 1 :(得分:2)
您可以对矩阵的sapply
元素使用unique
来获得所有元素的向量,
t(sapply(unique(as.vector(f)),function(x)colSums(f==x)))
# [,1] [,2] [,3]
# A 1 0 1
# B 2 3 1
# C 0 0 1
注意:上述解决方案是@akrun
数据:
f <- matrix(data = c("A","B","A","B","B","B","B","B","C"), byrow = TRUE, nrow = 3)