dplyr按序列复制每一行

Wil*_*car 3 r dplyr

Dplyr:如何根据整数序列重复每一行(1:3)

我正在办理登记册(关于比利时的例子):

country<- c("belg")
country <- as.data.frame(country)
Run Code Online (Sandbox Code Playgroud)

该注册包含3页:

library(dplyr)

country2 <- country %>%
   slice(rep(1:n(), each=3)) %>% 
   mutate(pages = row_number())
Run Code Online (Sandbox Code Playgroud)

我的输出:

  country page 
  belg     1
  belg     2
  belg     3
Run Code Online (Sandbox Code Playgroud)

预期结果:每个Register'pages包含三行(根据整数序列重复每一行(1:3))

  country page row_id
  belg     1   1
  belg     1   2
  belg     1   3 
  belg     2   1
  belg     2   2
  belg     2   3
  ...
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

将它添加到我的dplyr管道:

     %>%
     group_by(pages) %>% 
     mutate(row_id = seq(1:3)) %>%
     ungroup()
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 7

您可以创建一个包含1:3的列表列,然后将其删除:

library(dplyr); library(tidyr)
df %>% mutate(row_id = list(seq_len(3))) %>% unnest()

#  country page row_id
#1    belg    1      1
#2    belg    1      2
#3    belg    1      3
#4    belg    2      1
#5    belg    2      2
#6    belg    2      3
#7    belg    3      1
#8    belg    3      2
#9    belg    3      3
Run Code Online (Sandbox Code Playgroud)
dput(df)
structure(list(country = structure(c(1L, 1L, 1L), .Label = "belg", class = "factor"), 
    page = 1:3), .Names = c("country", "page"), class = "data.frame", row.names = c(NA, 
-3L))
Run Code Online (Sandbox Code Playgroud)