0

I want to be able to see how many times a value has already been listed in the dataset. Thank you!!

test = c("a", "a", "b", "b", "a", "c") I want to be able to return new_variable = c(1, 2, 1, 2, 3, 1) based on the information above

Kevin W
  • 91
  • 2
  • 9
  • Is test a vector or a dataframe? – Henry Cyranka Dec 19 '18 at 23:48
  • I'm guessing I'll have to sort and then create a for loop? or a sequence function? – Kevin W Dec 19 '18 at 23:48
  • test is a vector – Kevin W Dec 19 '18 at 23:49
  • Essentially you are doing this - https://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame - where the variable and the group are the same - `as.numeric(ave(test,test,FUN=seq_along))` as a base example or you could use one of the countless other methods using your favourite out of packages like `dplyr` or `data.table` – thelatemail Dec 19 '18 at 23:52

1 Answers1

0

Using tidyverse

library(tidyverse)


test = c("a", "a", "b", "b", "a", "c")

resulting_vector <- test %>% as_tibble() %>%
    group_by(value) %>%
    mutate(total = row_number()) %>%
    pull(total)

resulting_vector
Henry Cyranka
  • 2,970
  • 1
  • 16
  • 21