ah bon
ah bon

Reputation: 10011

Add new column of rows frequency in R

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

Answers (2)

Chris Ruehlemann
Chris Ruehlemann

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 matching the corresponding rows in xand 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

GKi
GKi

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

Related Questions