如何在 r 中显示每个级别的所有值?
How to show all the values in each level in r?
我有一个如下所示的数据集:
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
OP 创建了一个包含 2 列的矩阵。这需要先转换为 data.frame 或 data.table,然后再应用找到的众多解决方案之一 here.
# 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 要求显示 每个级别 值的种类 (强调我的)。
我有一个如下所示的数据集:
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
OP 创建了一个包含 2 列的矩阵。这需要先转换为 data.frame 或 data.table,然后再应用找到的众多解决方案之一 here.
# 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 要求显示 每个级别 值的种类 (强调我的)。