vector - Counting number of appeareances of a certain value in r -


let's have vector a <- c(1,2,3,4,1,5,6,1,7) , want function return number of repetitions of each value. results want c(1,1,1,1,2,1,1,3,1) - because number 1 being repeated 3 times.

the second question - how function return c(1,0,0,0,2,0,0,3,0) values above? count elements being repeated , others 0?

thank you!

you can use ave function:

ave(rep(1, length(a)), a, fun=cumsum) # [1] 1 1 1 1 2 1 1 3 1 

following @lmo's comment, second part:

alldups <- duplicated(a) | duplicated(a, fromlast = true) res <- ave(rep(1, length(a)), a, fun=cumsum) res[!alldups] <- 0 # [1] 1 0 0 0 2 0 0 3 0 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -