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

Transform count column into number of rows

I would like to transform a column of values into data that R will read as frequency. For example, if I counted 3 birds at one location, I would like that to show up as three rows, each row with one bird. In other words, I would like to go from df1 to df2:

df1 <- data.frame(lat = c(35, 40, 42), 
                  lon = c(-96, -101, -97), 
                  nbird = c( 2,  4, 2))  

df2 <- data.frame(lat = c(35, 35, 40, 40, 40, 40, 42, 42), 
                  lon = c(-96, -96, -101,-101, -101, -101, -97, -97), 
                  nbird = c( 1, 1, 1, 1, 1, 1, 1, 1))

>Solution :

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

Using tidyr::uncount you could do:

library(tidyr)
library(dplyr)

uncount(df1, nbird) %>% 
  mutate(nbird = 1)
#>   lat  lon nbird
#> 1  35  -96     1
#> 2  35  -96     1
#> 3  40 -101     1
#> 4  40 -101     1
#> 5  40 -101     1
#> 6  40 -101     1
#> 7  42  -97     1
#> 8  42  -97     1
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