任何人都知道如何自己获取列中每个元素的计数

时间:2015-06-17 14:31:54

标签: r count dataframe

例如,这是我的数据

SYSTEM.BASE.TOPIC

是否有任何可以生成矢量或列的函数,如

mydata
  v
1 1
2 1
3 2
4 2
5 2
6 3

我尝试了 v counts 1 1 2 2 1 2 3 2 3 4 2 3 5 2 3 6 3 1 的方法,但失败了

sum()

5 个答案:

答案 0 :(得分:4)

ave的另一个基本R选项:

within(mydata, counts <- ave(v, v, FUN=length))

答案 1 :(得分:2)

library(dplyr)
mutate(group_by(mydata,v),count=(length(v)))

答案 2 :(得分:1)

使用基数R:

SELECT [LineNo], [Month], Base, Budget
FROM test
CROSS APPLY(VALUES -- unpivot columns into rows
    ('January', BaseJanuary, BudgetJanuary) -- generate row for jan
  , ('February', BaseFebruary, BudgetFebruary) -- generate row for feb
) ca ([Month], Base, Budget)

答案 3 :(得分:1)

使用ddply

library(plyr)
ddply(mydata, .(v), mutate, counts = length(v))

#  v counts
#1 1      2
#2 1      2
#3 2      3
#4 2      3
#5 2      3
#6 3      1

lapply

do.call(rbind, lapply(split(mydata, mydata$v), 
        function(x){ x$counts = length(x$v); x}))

#    v counts
#1.1 1      2
#1.2 1      2
#2.3 2      3
#2.4 2      3
#2.5 2      3
#3   3      1

答案 4 :(得分:-3)

as.data.frame(table(a))

我会用这样的东西:

a Freq
1  1    2
2  2    3
3  3    1

$('.nav-tabs li a').click(function (e) { //get selected href var href = $(this).attr('href'); //set all nav tabs to inactive $('.nav-tabs li').removeClass('active'); //get all nav tabs matching the href and set to active $('.nav-tabs li a[href="'+href+'"]').closest('li').addClass('active'); //active tab $('.tab-pane').removeClass('active'); $('.tab-pane'+href).addClass('active'); })