Counting the number of elements with the values of x in a vector

后端 未结 19 1328
闹比i
闹比i 2020-11-22 02:44

I have a vector of numbers:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

How can I hav

19条回答
  •  不知归路
    2020-11-22 03:22

    One more way i find convenient is:

    numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,453,435,324,34,456,56,567,65,34,435)
    (s<-summary (as.factor(numbers)))
    

    This converts the dataset to factor, and then summary() gives us the control totals (counts of the unique values).

    Output is:

    4   5  23  34  43  54  56  65  67 324 435 453 456 567 657 
    2   1   2   2   1   1   2   1   2   1   3   1   1   1   1 
    

    This can be stored as dataframe if preferred.

    as.data.frame(cbind(Number = names(s),Freq = s), stringsAsFactors=F, row.names = 1:length(s))

    here row.names has been used to rename row names. without using row.names, column names in s are used as row names in new dataframe

    Output is:

         Number Freq
    1       4    2
    2       5    1
    3      23    2
    4      34    2
    5      43    1
    6      54    1
    7      56    2
    8      65    1
    9      67    2
    10    324    1
    11    435    3
    12    453    1
    13    456    1
    14    567    1
    15    657    1
    

提交回复
热议问题