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
You can just use table()
:
> a <- table(numbers)
> a
numbers
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
Then you can subset it:
> a[names(a)==435]
435
3
Or convert it into a data.frame if you're more comfortable working with that:
> as.data.frame(table(numbers))
numbers Freq
1 4 2
2 5 1
3 23 2
4 34 2
...
You can change the number to whatever you wish in following line
length(which(numbers == 4))
There is also count(numbers)
from plyr
package. Much more convenient than table
in my opinion.
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
One option could be to use vec_count()
function from the vctrs
library:
vec_count(numbers)
key count
1 435 3
2 67 2
3 4 2
4 34 2
5 56 2
6 23 2
7 456 1
8 43 1
9 453 1
10 5 1
11 657 1
12 324 1
13 54 1
14 567 1
15 65 1
The default ordering puts the most frequent values at top. If looking for sorting according keys (a table()
-like output):
vec_count(numbers, sort = "key")
key count
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
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435 453,435,324,34,456,56,567,65,34,435)
> length(grep(435, numbers))
[1] 3
> length(which(435 == numbers))
[1] 3
> require(plyr)
> df = count(numbers)
> df[df$x == 435, ]
x freq
11 435 3
> sum(435 == numbers)
[1] 3
> sum(grepl(435, numbers))
[1] 3
> sum(435 == numbers)
[1] 3
> tabulate(numbers)[435]
[1] 3
> table(numbers)['435']
435
3
> length(subset(numbers, numbers=='435'))
[1] 3