Let's say my data looks like this:
df
ID Location
1 54
2 35
3 54
4 35
5 71
I'm interested in finding the frequency of visits to a given location, and then assigning that frequency (i.e. sum) to a new column based on the value in the Location column.
To begin, I've tried using the table
function:
count<-as.data.frame(table(df))
count
var1 freq
54 2
35 2
71 1
From here, I'd like to create a new column in df, called count, which assigns freq=2 for each ID which corresponds to Location=54, for example. I.e., df would now look something like this:
df
ID Location count
1 54 2
2 35 2
3 54 2
4 35 2
5 71 1
My real data contains too many Location values for me to feasibly write an ifelse statement to conditionally assign these count values. I'm not sure how to accomplish in an efficient manner (I could also create a null column and use the replace
function in dplyr, but that would be similarly laborious. Any tips?
Thanks!