Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Percentage that each element appears in a vector

I am looking for a way to take a vector and return the percentage that each element appears.

See below for the input vector and the expected result.

InputVector<-c(1,1,1,1,1,2,2,2,3,3)

ExpectedResult<-data.frame(Value=c(1,2,3), Percentile=c(0.5,0.3,0.2))

In this case, 1 appears 50% of the time, 2 appears 30% and 3 appears 20% of the time.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Get the frequency count with table on the vector, apply proportions to convert it to proportions, and then reshape the named vector to a two column data.frame with stack in base R

stack(proportions(table(InputVector)))[2:1]

-output

  ind values
1   1    0.5
2   2    0.3
3   3    0.2

Or use tidyverse to get the frequency count and apply proportions on the frequency column ‘n’ to get the percentile

library(dplyr)
tibble(Value = InputVector) %>%
   count(Value) %>% 
   mutate(Percentile = proportions(n), n = NULL)

-output

# A tibble: 3 × 2
  Value Percentile
  <dbl>      <dbl>
1     1        0.5
2     2        0.3
3     3        0.2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading