R 计算向量中每个元素的频率
我在寻找一种方法来计算向量中每个元素的频率R 计算向量中每个元素的频率,r,vector,count,frequency,R,Vector,Count,Frequency,我在寻找一种方法来计算向量中每个元素的频率 ex <- c(2,2,2,3,4,5) 有一个简单的命令吗 rep(table(ex), table(ex)) # 2 2 2 3 4 5 # 3 3 3 1 1 1 如果不需要标签,可以将包装为.vector() 我要补充一点(因为它似乎有某种关联),如果您只需要连续值,可以使用rle而不是table: ex2 = c(2, 2, 2, 3, 4, 2, 2, 3, 4, 4) rep(rle(ex2)$lengths, rle(ex
ex <- c(2,2,2,3,4,5)
有一个简单的命令吗
rep(table(ex), table(ex))
# 2 2 2 3 4 5
# 3 3 3 1 1 1
如果不需要标签,可以将包装为.vector()
我要补充一点(因为它似乎有某种关联),如果您只需要连续值,可以使用rle
而不是table
:
ex2 = c(2, 2, 2, 3, 4, 2, 2, 3, 4, 4)
rep(rle(ex2)$lengths, rle(ex2)$lengths)
# [1] 3 3 3 1 1 2 2 1 2 2
正如注释中指出的,对于大型向量,计算一个表可能会很昂贵,因此只计算一次更有效:
tab = table(ex)
rep(tab, tab)
# 2 2 2 3 4 5
# 3 3 3 1 1 1
如果不需要标签,可以将包装为.vector()
我要补充一点(因为它似乎有某种关联),如果您只需要连续值,可以使用rle
而不是table
:
ex2 = c(2, 2, 2, 3, 4, 2, 2, 3, 4, 4)
rep(rle(ex2)$lengths, rle(ex2)$lengths)
# [1] 3 3 3 1 1 2 2 1 2 2
正如注释中指出的,对于大型向量,计算一个表可能会很昂贵,因此只计算一次更有效:
tab = table(ex)
rep(tab, tab)
# 2 2 2 3 4 5
# 3 3 3 1 1 1
你可以用
ex <- c(2,2,2,3,4,5)
outcome <- ave(ex, ex, FUN = length)
ex您可以使用
ex <- c(2,2,2,3,4,5)
outcome <- ave(ex, ex, FUN = length)
ex同样,对于rle
一个你可以用(rle(ex),rep(length,length))来避免多次rle
计算:)另外,ave(ex,ex,FUN=length)
同样,对于rle
一个你可以用(rle(ex),rep(length,length))
来避免多次rle
计算:),ave(ex,ex,FUN=length)