我正在努力解决一个可能很简单的问题。我有1列n列的数据框(n是3的倍数)。我想在第二列添加整数,例如:1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,..如何使用dplyr作为不同长度的行(3的所有倍数)的通用解决方案。
我尝试了这个:
df <- tibble(Col1 = c(1:12)) %>%
mutate(Col2 = rep(1:4, each=3))
这有效。但我想为n行提供解决方案,每行= 3。非常感谢!
您可以在中指定each
和length.out
参数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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句