2

I would like to count the instances of a Employee ID in a column and write back the results to a new column in my dataframe. So far I am able to count the instances and display the results in the R Studio console, but I'm not sure how to write the results back. Here is what I have tested successfully:

ids<-BAR$`Employee ID`
counts<-data.frame(table(ids))
counts

And here are the returned results:

1   00000018    1
2   00000179    1
3   00001045    1
4   00002729    1
5   00003095    2
6   00003100    1

Thanks!

camille
  • 16,432
  • 18
  • 38
  • 60
Chris2015
  • 1,030
  • 7
  • 28
  • 42
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making a reproducible example. Is the question just how to assign a vector or something else to a data frame? Write the results back to what? – camille Apr 09 '20 at 20:27

2 Answers2

0

If we need to create a column, use add_count

library(dplyr)
BAR1 <- BAR %>%
          add_count(`Employee ID`)

table returns the summarised output. If we want to create a column in the original data

BAR1$n <- table(ids)[as.character(BAR$`Employee ID`)]
akrun
  • 874,273
  • 37
  • 540
  • 662
0

If you use a data.table you will be able to do this quickly, especially with larger datasets, using .N to count number of occurrences per grouping variable given in by.

# Load data.table 
library(data.table)
# Convert data to a data.table 
setDT(BAR)
# Count and assign counts per level of ID
BAR[, count := .N, by = ID]
rg255
  • 4,119
  • 3
  • 22
  • 40