我有一个如下所示的数据集:
first <- c(5:14)
second <- rep(c("a","b"),5)
c <- cbind(first, second)
c
first second
[1,] "5" "a"
[2,] "6" "b"
[3,] "7" "a"
[4,] "8" "b"
[5,] "9" "a"
[6,] "10" "b"
[7,] "11" "a"
[8,] "12" "b"
[9,] "13" "a"
[10,] "14" "b"
如您所见,有两个级别(a和b)
我想做一个摘要,显示每个级别中的值是什么类型。
a : 5,7,9,11,13
b : 6,8,10,12,14
答案 0 :(得分:1)
OP创建了一个包含2列的矩阵。在应用找到here的众多解决方案之一之前,首先需要将其转换为data.frame或data.table。
# create matrix the way the OP has done it but using a different name
# in order to avoid name conflicts with the c() function
first <- c(5:14)
second <- rep(c("a", "b"), 5)
mat <- cbind(first, second)
# one possible approach
library(data.table)
as.data.table(mat)[, .(first = toString(unique(first))), by = second]
second first 1: a 5, 7, 9, 11, 13 2: b 6, 8, 10, 12, 14
请注意,unique()
的使用是出于OP的要求,即在每个级别显示 类型的 (强调我的)。