Count if in R w?

Hi,

Really struggling to get the desired output.

I have a vector containing a range of characters.
I also have a data frame containing a range of categories.

Current vector:

vector = c("1","1","2","3","3","3")

Current dataframe:

df <- data.frame(
   Door.Number = c("1", "2", "3")
)

How would I create a new column within the dataframe, with the count of records in the vector?

Desired Output

data.frame(
   Door.Number = c("1", "2", "3"),
         Count = c(2, 1, 3)
)

I've tried methods like the one below with no luck. Just seems to create a column with the total.

mutate(count = sum(df[,1] %in% vector))

Thanks for all guidance, help!

One way to do this is by using group_by and summarise count() from dplyr.

library(dplyr)
as_tibble(vector) %>%
  count(value, name = "count") %>% 
  left_join(df, ., by = c("Door.Number" = "value"))

edit:
PS NB I think the left_join will leave an NA instead of a zero for any rows that don't match (where count is 0 it will just be omitted), so to be a really thorough solution you would add a line to replace NA with 0 in the final joined count column.

Thank you!

So simple...

But didn't even cross my mind to do this!

Haha! Well, like anything, it's simple if you know it, not always obvious if you don't. It's all just stuff learned along the way.
And as ever with R, there's more than one way to do it.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.