2

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))
Nazer
  • 3,654
  • 8
  • 33
  • 47

2 Answers2

4

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
stefan
  • 90,330
  • 6
  • 25
  • 51
1

With base R:

df2 <- df1[rep(1:nrow(df1), times = df1$nbird), ] 
df2$nbird <- 1L
df2

#>     lat  lon nbird
#> 1    35  -96     1
#> 1.1  35  -96     1
#> 2    40 -101     1
#> 2.1  40 -101     1
#> 2.2  40 -101     1
#> 2.3  40 -101     1
#> 3    42  -97     1
#> 3.1  42  -97     1
student t
  • 51
  • 3