I would like to assign a value in a new column (i.e.: country_count) of the amount of times a specific string occurs (in total) in my data frame.
country = c("DE", "FR", "FR", "FR", "NL","DE")
data_frame =data.frame(country)
This would be the resulting data frame.
country = c("DE", "FR", "FR", "FR", "NL","DE")
country_count = c(2, 3, 3, 3, 1,2)
data_frame =data.frame(country,country_count)
I am aware that I can simply run table(data_frame$country) to get the same result, but I would like to have the values in an additional column because ultimately I want to assign a different value to the strings (in my case countries) below a certain threshold.
You could use dplyr:
library(dplyr)
data_frame %>%
add_count(country, name="country_count")
returns
country country_count
1 DE 2
2 FR 3
3 FR 3
4 FR 3
5 NL 1
6 DE 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With