Add column with counts of another

r

Solution

You may try `ave`:

# first, convert 'gender' to class character
df$gender <- as.character(df$gender)

df$count <- as.numeric(ave(df$gender, df$gender, FUN = length))
df
#   gender age count
# 1      m  18     4
# 2      f  14     2
# 3      m  18     4
# 4      m  18     4
# 5      m  15     4
# 6      f  15     2

Update following @flodel's comment - thanks!

`df <- transform(df, count = ave(age, gender, FUN = length))`

Problem

I have a data frame `df` that looks like the following where the `gender` column is a `factor` with two levels: ``` gender age m 18 f 14 m 18 m 18 m 15 f 15 ``` I would like to add a new column called `count` that simply reflects the number of times that `gender` level appears in the data frame. So, ultimately, the data frame would look like: ``` gender age count m 18 4 f 14 2 m 18 4 m 18 4 m 15 4 f 15 2 ``` I know that I can do `table(df$gender)` that gives me the number of times the factor appears, but I do not know how to translate those results into a new column in `df`. I'm wondering how can I use the `table` function--or is there a better way to achieve my new column?

Original source

Related problems