计算向量中具有 x 值的元素的数量 [英] Counting the number of elements with the values of x in a vector

查看:35
本文介绍了计算向量中具有 x 值的元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字向量:

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

如何让 R 计算一个值 x 在向量中出现的次数?

How can I have R count the number of times a value x appears in the vector?

推荐答案

你可以直接使用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

如果您更愿意使用它,也可以将其转换为 data.frame:

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
...

这篇关于计算向量中具有 x 值的元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆