2017-07-10 25 views
1

我一直在試圖找到一種方法來取代R因子的計數/頻率。例如,下面的數據幀產生這樣的用它的計數替換因子列

t <- data.frame(color = c('red', 'blue', 'red', 'green', 'red', 'red', 'green')) 

    color 
1 red 
2 blue 
3 red 
4 green 
5 red 
6 red 
7 green 

我很感興趣,它的發生次數的替代因素,所以它可以像這樣

color 
1 4 
2 1 
3 4 
4 2 
5 4 
6 4 
7 2 

由於水平red具有計數4,blue 1和​​2.

到目前爲止,我所有的嘗試似乎都過於複雜(apply,merge,table,...),並且他們沒有生成我所需要的。

有關如何解決此問題的任何建議?

+0

我刪除了不必要的'as.factor'線,因爲它是由'data.frame' –

+0

@RichScriven感謝編輯和格式化隱式進行。 – user3276768

回答

2

您可以製作矢量表,然後使用各級的整數值進行展開。

t$color <- with(t, tabulate(color)[color]) 
t 
# color 
# 1  4 
# 2  1 
# 3  4 
# 4  2 
# 5  4 
# 6  4 
# 7  2 

另一種選擇是使用ave()length()

with(t, ave(seq_along(color), color, FUN = length)) 
# [1] 4 1 4 2 4 4 2 
0
x <- read.table(text=" color 
       1 red 
       2 blue 
       3 red 
       4 green 
       5 red 
       6 red 
       7 green", header=TRUE) 

data.frame(x, count=sapply(1:nrow(x), function(i) sum(x$color==x$color[i]))) 
# color count 
# 1 red  4 
# 2 blue  1 
# 3 red  4 
# 4 green  2 
# 5 red  4 
# 6 red  4 
# 7 green  2 
0

使用data.table

setDT(t) 
t[, color2 := .N, by = color][, .(color = color2)] 

    color 
1:  4 
2:  1 
3:  4 
4:  2 
5:  4 
6:  4 
7:  2