Esc*_*her 28 r frequency count
我有一个mydf大约2500行的data.frame .这些行对应于colum 1中的69个对象类mydf$V1,我想计算每个对象类有多少行.我可以通过以下方式获得这些类的因子:
objectclasses = unique(factor(mydf$V1, exclude="1"));
什么是计算每个对象类的行的简洁R方法?如果这是任何其他语言,我将遍历一个带循环的数组并保持计数,但我是R编程的新手,并且我正在尝试利用R的矢量化操作.
Pau*_*tra 43
或者使用dplyr图书馆:
library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))
注意使用%>%,类似于在bash中使用管道.实际上,上面的代码管道dat输入group_by,并且该操作的结果被输入summarise.
结果是:
Source: local data frame [26 x 2]
   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1
有关更多上下文的信息,请参阅dplyr介绍,有关各个功能的详细信息,请参阅文档.
ags*_*udy 31
这有两种方法:
set.seed(1)
tt <- sample(letters,100,rep=TRUE)
## using table
table(tt)
tt
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 
## using tapply
tapply(tt,tt,length)
a b c d e f g h i j k l m n o p q r s t u v w x y z 
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1 
And*_* T. 22
使用plyr包:
library(plyr)
count(mydf$V1)
它会返回每个值的频率.
akr*_*run 15
运用 data.table
 library(data.table)
 setDT(dat)[, .N, keyby=ID] #(Using @Paul Hiemstra's `dat`)
或使用 dplyr 0.3
 res <- count(dat, ID)
 head(res)
 #Source: local data frame [6 x 2]
 #  ID n
 #1  a 2
 #2  b 3
 #3  c 3
 #4  d 3
 #5  e 2
 #6  f 4
要么
  dat %>% 
      group_by(ID) %>% 
      tally()
要么
  dat %>% 
      group_by(ID) %>%
      summarise(n=n())
小智 6
另一种方法是应用 n() 函数来计算观察次数
library(dplyr)
library(magrittr)
data %>% 
  group_by(columnName) %>%
  summarise(Count = n())