Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new column containing the total amount of occurrences of a string in R

Tags:

r

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.

like image 977
peter_c Avatar asked Dec 06 '25 04:12

peter_c


1 Answers

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
like image 123
Martin Gal Avatar answered Dec 07 '25 20:12

Martin Gal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!