我有一个数字向量:
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值在向量中出现的次数?
我有一个数字向量:
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值在向量中出现的次数?
当前回答
你可以创建一个函数来得到结果。
# your list
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
453,435,324,34,456,56,567,65,34,435)
function1<-function(x){
if(x==value){return(1)}else{ return(0) }
}
# set your value here
value<-4
# make a vector which return 1 if it equal to your value, 0 else
vector<-sapply(numbers,function(x) function1(x))
sum(vector)
结果:2
其他回答
你可以使用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
然后你可以对它进行子集:
> a[names(a)==435]
435
3
或者将它转换为data.frame,如果你更喜欢使用它:
> as.data.frame(table(numbers))
numbers Freq
1 4 2
2 5 1
3 23 2
4 34 2
...
也有计数(数字)从plyr包。在我看来,比餐桌方便多了。
您可以在下面一行中将数字更改为您希望的任何数字
length(which(numbers == 4))
这里有一个快速而肮脏的方法:
x <- 23
length(subset(numbers, numbers==x))
在R中有一个标准函数
汇总(数字)