Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding frequency column to each observation

everyone!
Here’s the problem , I have this dataset and I need to add a column with the frequency of each pet, I don’t want a new dataframe with the statistics. See, dog and cat appears 6 time each, I need a column with value of 6 beside each dog and cat. Then I’ll be able to make relational studies, which is why creating a new dataframe with summary is not an option

   id    answer
   <chr> <chr> 
 1 1     cat   
 2 1     dog   
 3 2     bird  
 4 3     cat   
 5 3     dog   
 6 3     fish  
 7 4     dog   
 8 5     turtle
 9 6     cat   
10 7     cat   
11 7     fish  
12 7     dog   
13 7     cat   
14 8     dog   
15 8     cat   
16 9     bird  
17 9     dog  

by the end, it should look like this:

Output that I'm looking for

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using data.table you can group by frequency with .N

library(data.table)
your_table = as.data.table(your_table)
your_table[,freq := .N, by = answer]

#     id answer freq
#  1:  1    cat    6
#  2:  1    dog    6
#  3:  2   bird    2
#  4:  3    cat    6
#  5:  3    dog    6
#  6:  3   fish    2
#  7:  4    dog    6
#  8:  5 turtle    1
#  9:  6    cat    6
# 10:  7    cat    6
# 11:  7   fish    2
# 12:  7    dog    6
# 13:  7    cat    6
# 14:  8    dog    6
# 15:  8    cat    6
# 16:  9   bird    2
# 17:  9    dog    6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading