phaser
phaser

Reputation: 625

add duplicates to some rows and change order of rows in a data frame

I would like to duplicate some rows in a data frame.

df <- structure(list(yrmonth = structure(c(17167, 17167, 17167, 17198, 
17198, 17198, 17226, 17226, 17226, 17257, 17257, 17257), class = "Date"), 
    index = structure(c(2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 
    1L, 3L), .Label = c("E-W", "N-S", "OS"), class = "factor"), 
    N = c(2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 2, 1), data = c(129, 
    141, 27, 150.5, 209, 87, 247.5, 243, 188, 223, 226.5, 170
    )), .Names = c("yrmonth", "index", "N", "data"), row.names = 31:42, class = "data.frame")

I want all the rows with "N-S" label to appear twice, and all the rows with "OS" label to appear three times. Then I would like to reorder the data frame so that the labels are "E-W", "OS", "N-S", "OS", "N-S", "OS".

I would like the data frame to look like this:

      yrmonth index N  data
31   2017-01-01   N-S 2 129.0
33   2017-01-01    OS 1  27.0
31.1 2017-01-01   N-S 2 129.0
33.1 2017-01-01    OS 1  27.0
32   2017-01-01   E-W 2 141.0
33.2 2017-01-01    OS 1  27.0
34   2017-02-01   N-S 2 150.5
36   2017-02-01    OS 1  87.0
34.1 2017-02-01   N-S 2 150.5
36.1 2017-02-01    OS 1  87.0
35   2017-02-01   E-W 2 209.0
36.2 2017-02-01    OS 1  87.0

Upvotes: 0

Views: 61

Answers (2)

www
www

Reputation: 39154

df2 is the final output.

library(tidyverse)

df2 <- df %>%
  mutate(index = ifelse(index %in% "N-S", list(rep("N-S", 2)),
                        ifelse(index %in% "OS", list(rep("OS", 3)), list("E-W")))) %>%
  unnest() %>%
  group_by(yrmonth) %>%
  mutate(ID = c(1, 3, 5, 2, 4, 6)) %>%
  arrange(yrmonth, ID) %>%
  select(yrmonth, index, N, data)

Upvotes: 2

roarkz
roarkz

Reputation: 831

Here is a solution to this exact problem, but it is not very flexible.

 df$freq <- 1
 df[df$index == "N-S", ]$freq <- 2
 df[df$index == "OS", ]$freq <- 3
 df[rep(row.names(df), df$freq), 1:4]

Upvotes: 3

Related Questions