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

pivot_longer repeat entries instead of counting them

I want to use pivot_longer to create a datatable which is easy to visualize.
The code I am using looks something like this:

library(tidyverse)

relig_income %>%
  pivot_longer(!religion, names_to = "income", values_to = "count")

The output looks like this (not really, I changed the count column):

   religion income             count
   <chr>    <chr>              <dbl>
 1 Agnostic <$10k                 3
 2 Agnostic $10-20k               2
   ....

However, for my purposes, it would be much more useful if the output would look like this:

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

   religion income             
   <chr>    <chr>              
 1 Agnostic <$10k                
 2 Agnostic <$10k                
 3 Agnostic <$10k                
 4 Agnostic $10-20k               
 5 Agnostic $10-20k               
   ...               

So, basically, in the end there should only be two columns left and the income column should just repeat the specific value as often as the entry in the count column.
Is there an option within pivot_longer or another R function which conveniently transforms the dataframe?

Any help is much appreciated!

>Solution :

You can simply do uncount From package tidyr:

library(tidyverse)

relig_income %>%
  pivot_longer(!religion, names_to = "income", values_to = "count") %>%
  uncount(count)

# A tibble: 35,556 x 2
   religion income
   <chr>    <chr> 
 1 Agnostic <$10k 
 2 Agnostic <$10k 
 3 Agnostic <$10k 
 4 Agnostic <$10k 
 5 Agnostic <$10k 
 6 Agnostic <$10k 
 7 Agnostic <$10k 
 8 Agnostic <$10k 
 9 Agnostic <$10k 
10 Agnostic <$10k 
# ... with 35,546 more rows
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