向某些行添加重复项并更改数据框中的行顺序

时间:2017-06-30 18:54:31

标签: r

我想在数据框中复制一些行。

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")

我希望所有的行都带有&#34; N-S&#34;标签出现两次,所有行用&#34; OS&#34;标签出现三次。然后我想重新排序数据框,以便标签是&#34; E-W&#34;,&#34; OS&#34;,&#34; N-S&#34;,&#34; OS& #34;,&#34; N-S&#34;,&#34; OS&#34;。

我希望数据框看起来像这样:

      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

2 个答案:

答案 0 :(得分:3)

这是一个解决这个问题的方法,但它不是很灵活。

 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]

答案 1 :(得分:2)

df2是最终输出。

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)