dplyr按序列复制每行 [英] dplyr duplicate each line by a sequence
本文介绍了dplyr按序列复制每行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dplyr:如何基于整数序列(1:3)重复每一行
Dplyr: how to repeat each row based on a sequence of integers (1:3)
我正在研究寄存器(例如比利时):
I am working on a register (about Belgium for exemple) :
country<- c("belg")
country <- as.data.frame(country)
注册表包含3页:
library(dplyr)
country2 <- country %>%
slice(rep(1:n(), each=3)) %>%
mutate(pages = row_number())
我的输出:
country page
belg 1
belg 2
belg 3
预期结果:
每个寄存器的页面包含三行(根据整数序列(1:3)重复每一行)
Expected result : Each Register'pages contains three rows (repeat each row based on a sequence of integers (1:3))
country page row_id
belg 1 1
belg 1 2
belg 1 3
belg 2 1
belg 2 2
belg 2 3
...
我怎么ied:
将此添加到dplyr的管道中:
Adding this to my dplyr's pipe :
%>%
group_by(pages) %>%
mutate(row_id = seq(1:3)) %>%
ungroup()
推荐答案
另一个选择是将粘贴
作为字符串然后使用 separate_rows
拆分行
Another option is to paste
as a string and then with separate_rows
split the rows
library(tidyverse)
df %>%
mutate(row_id = toString(seq_len(3))) %>%
separate_rows(row_id)
# 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
这篇关于dplyr按序列复制每行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文