计算唯一值

假设我有:


v = rep(c(1,2, 2, 2), 25)

现在,我想计算每个唯一值出现的次数。unique(v) 返回唯一值是多少,但不是多少。


> unique(v)

[1] 1 2

我想要能给我的东西


length(v[v==1])

[1] 25

length(v[v==2])

[1] 75

但作为更一般的单行代码:)有些类似(但不太完全)的东西:


#<doesn't work right> length(v[v==unique(v)])


长风秋雁
浏览 472回答 3
3回答

红颜莎娜

也许桌子是你所追求的?dummyData = rep(c(1,2, 2, 2), 25)table(dummyData)# dummyData#&nbsp; 1&nbsp; 2&nbsp;# 25 75## or another presentation of the same dataas.data.frame(table(dummyData))#&nbsp; &nbsp; dummyData Freq#&nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1&nbsp; &nbsp;25#&nbsp; 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2&nbsp; &nbsp;75

幕布斯6054654

正如Chase所建议的,table()函数是一个很好的方法。如果要分析大型数据集,另一种方法是在数据表包中使用.N函数。确保通过以下方式安装了数据表包install.packages("data.table")码:# Import the data.table packagelibrary(data.table)# Generate a data table object, which draws a number 10^7 times&nbsp;&nbsp;# from 1 to 10 with replacementDT<-data.table(x=sample(1:10,1E7,TRUE))# Count Frequency of each factor levelDT[,.N,by=x]
打开App,查看更多内容
随时随地看视频慕课网APP