Bartek Taciak Bartek Taciak - 1 month ago 10
R Question

Counts of duplicate rows as a new column without grouping of duplicate rows

My data looks like this one:

A B C
1 a 1 ff
2 b 1 re
3 c 1 sd
5 a 2 as
6 c 4 fe
7 d 5 tt
8 d 5 tt
9 d 9 oi


I want to add a new column D, which will contain how many times an element from the column A is repeated in all data, like this:

A B C D
1 a 1 ff 2
2 b 1 re 1
3 c 1 sd 2
5 a 2 as 2
6 c 4 fe 2
7 d 5 tt 3
8 d 5 tt 3
9 d 9 oi 3


I don't want to simplify my data grouping raws like in this thread:
https://stat.ethz.ch/pipermail/r-help/2011-March/270481.html

Thanks in advance for any help!

Answer

You can do it with table:

data <- read.table(text='A B C
a 1 ff
b 1 re
c 1 sd
a 2 as
c 4 fe
d 5 tt
d 5 tt
d 9 oi', header=T)

data$D <- table(data$A)[data$A]
Comments