0

Suppose there is a column with values

Website
Abc
Abc
Abc
Xyz
Xyz
Pqr
Uvw

Now i want to count how many times Abc or other names is in the column and write the count corresponding in the next column .

Website      Total
    Abc            3
    Abc            3
    Abc            3
    Xyz            2 
    Xyz            2
    Pqr            1
    Uvw            1

Can a function be created Without manually counting each website?

desertnaut
  • 46,107
  • 19
  • 109
  • 140

2 Answers2

2

1) ave Using the data shown reproducibly in the Note at the end, we can use ave to apply length to each group:

transform(DF, Count = ave(seq_along(Website), Website, FUN = length))

giving:

  Website Count
1     Abc     3
2     Abc     3
3     Abc     3
4     Xyz     2
5     Xyz     2
6     Pqr     1
7     Uvw     1

2) aggregate or without duplicates:

aggregate(list(Count = 1:nrow(DF)), DF["Website"], length)

giving:

  Website Count
1     Abc     3
2     Pqr     1
3     Uvw     1
4     Xyz     2

3) table Another approach is to create a table rather than a data.frame:

table(DF)

giving:

DF
Abc Pqr Uvw Xyz 
  3   1   1   2 

4) xtabs or we can use xtabs:

xtabs(DF)

giving:

Website
Abc Pqr Uvw Xyz 
  3   1   1   2 

Note

The input in reproducible form:

Lines <- "Website
Abc
Abc
Abc
Xyz
Xyz
Pqr
Uvw"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE, strip.white = TRUE)
G. Grothendieck
  • 211,268
  • 15
  • 177
  • 297
1

One option with tidyverse is add_count

library(dplyr)
df1 %>% 
  add_count(Website)
# A tibble: 7 x 2
#  Website     n
#  <chr>   <int>
#1 Abc         3
#2 Abc         3
#3 Abc         3
#4 Xyz         2
#5 Xyz         2
#6 Pqr         1
#7 Uvw         1
akrun
  • 674,427
  • 24
  • 381
  • 486