C.H.
C.H.

Reputation: 11

Count Values in a column and add the result next to the column in a new one

I have a fairly large dataset and want to count how often the value is mentioned in a specific column

Example:

A Home Away 
D Lisa Jill
D Jack Andre
C Jack Kirk
C Jane Jill 

I want to add a new column (called Count) and count how often every name in Home is mentioned.

A Home Away Count
D Lisa Jill 1
D Jack Andre 2
C Jack Kirk 2
C Jane Jill  1 

Thanks!

Upvotes: 1

Views: 87

Answers (2)

989
989

Reputation: 12935

Or using plyr (suppose your data is placed in df):

library(plyr)
join(df, as.data.frame(table(Home=df$Home)))

#   A Home  Away Freq
# 1 D Lisa  Jill    1
# 2 D Jack Andre    2
# 3 C Jack  Kirk    2
# 4 C Jane  Jill    1

Upvotes: 4

akrun
akrun

Reputation: 887851

We can use dplyr. After grouping by 'Home', get the number of rows (n()) and create that as new column with mutate

library(dplyr)
library(magrittr)
df1 %<>%
   group_by(Home) %>%
   mutate(Count = n())
#    A  Home  Away Count
#  <chr> <chr> <chr> <int>
#1     D  Lisa  Jill     1
#2     D  Jack Andre     2
#3     C  Jack  Kirk     2
#4     C  Jane  Jill     1

Or with data.table

library(data.table)
setDT(df1)[, Count := .N, by = Home]

Or with ave from base R

df1$Count <- with(df1, ave(seq_along(Home), Home, FUN = length))

Upvotes: 2

Related Questions