我对R很新,所以我确信有一个简单的方法可以做到这一点,但没有太多运气。
我有一个在运行时具有未知列数和行数的矩阵。如何返回具有匹配数据的行的计数次数?
如果我有矩阵m:
names <- c("John","Bob","John","Sarah","Jill","Sarah","John")
ages <- c("25","36","25","30","55","30","55")
home <- c("USA","Canada","USA","Canada","USA","Canada","Mexico")
m <- data.matrix(cbind(names,ages,home))
如何以此格式返回数据?
+-------+------+--------+-------+
| names | ages | home | count |
+-------+------+--------+-------+
| John | 25 | USA | 2 |
| Bob | 36 | Canada | 1 |
| Sarah | 30 | Canada | 2 |
| Jill | 55 | USA | 1 |
| John | 55 | Mexico | 1 |
+-------+------+--------+-------+
答案 0 :(得分:2)
你可以这样做:
library(data.table)
data.table(m)[,list(count=.N),by=list(names, ages, home)]
# names ages home count
#1: John 25 USA 2
#2: Bob 36 Canada 1
#3: Sarah 30 Canada 2
#4: Jill 55 USA 1
#5: John 55 Mexico 1