dplyr:使用数据帧中n次连续重复的整数来突变新列 [英] dplyr: Mutate a new column with sequential repeated integers of n time in a dataframe
本文介绍了dplyr:使用数据帧中n次连续重复的整数来突变新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力解决一个可能很简单的问题.我有1列n列的数据框(n是3的倍数).我想给第二列添加整数,例如:1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,..如何使用dplyr作为不同长度的行(3的倍数)的通用解决方案.
I am struggling with one maybe easy question. I have a dataframe of 1 column with n rows (n is a multiple of 3). I would like to ad a second column with integers like: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,.. How can I achieve this with dplyr as a general solution for different length of rows (all multiple of 3).
我尝试过:
df <- tibble(Col1 = c(1:12)) %>%
mutate(Col2 = rep(1:4, each=3))
这有效.但是我想为n行提供解决方案,每行= 3.非常感谢!
This works. But I would like to have a solution for n rows, each = 3 . Many thanks!
推荐答案
您可以在 rep
中指定每个
和 length.out
参数.
You can specify each
and length.out
parameter in rep
.
library(dplyr)
tibble(Col1 = c(1:12)) %>%
mutate(Col2 = rep(row_number(), each=3, length.out = n()))
# Col1 Col2
# <int> <int>
# 1 1 1
# 2 2 1
# 3 3 1
# 4 4 2
# 5 5 2
# 6 6 2
# 7 7 3
# 8 8 3
# 9 9 3
#10 10 4
#11 11 4
#12 12 4
这篇关于dplyr:使用数据帧中n次连续重复的整数来突变新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文