Reputation: 10011
Given a dataframe as follows:
var1 var2
1 a d
2 b e
3 b e
4 c f
5 c f
6 c f
How could count rows frequency by adding a new column frequency
? Thanks.
var1 var2 frequency
1 a d 1
2 b e 2
3 b e 2
4 c f 3
5 c f 3
6 c f 3
Upvotes: 0
Views: 505
Reputation: 21400
Here's a solution using match
(based on @GKi's data):
First, make a frequency table y
of the rows by collapsing them into strings:
y <- as.data.frame(table(apply(x, 1, paste0, collapse = " ")))
Then, transfer the frequencies to x
by match
ing the corresponding rows in x
and y
:
x$freq <- y$Freq[match(apply(x[,1:2], 1, paste0, collapse = " "), y$Var1)]
Result:
x
var1 var2 freq
1 a d 1
2 b e 2
3 b e 2
4 c f 3
5 c f 3
6 c f 3
Upvotes: 1
Reputation: 39647
You can use ave
with length
to count the rows frequency.
x$frequency <- ave(seq_len(nrow(x)), x, FUN=length)
x
# var1 var2 frequency
#1 a d 1
#2 b e 2
#3 b e 2
#4 c f 3
#5 c f 3
#6 c f 3
Data:
x <- read.table(header=TRUE, text=" var1 var2
1 a d
2 b e
3 b e
4 c f
5 c f
6 c f")
Upvotes: 2