创建重复值序列,其长度基于向量

问题描述 投票:0回答:1

如何使用数字序列填充“夜间”列,每个数字重复 3 次,并根据“站点”列重新启动该序列?我创建了一个表格来显示我想要实现的目标。这是我的问题的简化版本,我需要能够在更大的数据帧上使用代码。

|站点_日期_时间|站点|夜晚| |:......... |:..:|......:| |1_01012023_2200| 1| 1| |1_01012023_2300| 1| 1| |1_02012023_0000| 1| 1| |1_02012023_2200| 1| 2| |1_02012023_2300| 1| 2| |1_03012023_0000| 1| 2| |2_01012023_2100| 2| 1| |2_01012023_2200| 2| 1| |2_01012023_2300| 2| 1| |2_02012023_2200| 2| 2| |2_02012023_2300| 2| 2| |2_03012023_0000| 2| 2| |2_03012023_2200| 2| 3| |2_03012023_2300| 2| 3| |2_04012023_0000| 2| 3|

#Code to create basic data frame of Site
site <- c(rep(1,times=6), rep(2,times=9))
df <- data.frame(site)

我的主要问题是重新启动序列之前数字序列的长度不同(即每个站点的记录数不同)。 如果给定站点的行数相同,我可以使用以下内容。

library("dplyr")
library("data.table")

# Create data frame of the site vector, with the number of observations per site of equal length
site <- c(rep(1,times=6), rep(2,times=6))
df <- data.frame(site)
# Create sequence with repeated numbers 
group_by(df,site) %>% mutate(night = rep(c(1:3), each=3))

但我需要一个函数,允许我根据分组向量的长度而不是定义的长度创建具有重复数字的序列。我试图找到一种将rep()与seq_along()或rowid()结合起来的方法,但没有成功。

r dplyr sequence rep
1个回答
0
投票

您可以使用

length.out
rep()
参数。来自文档

length.out
:非负整数。输出向量的所需长度。其他输入将被强制为双向量并采用第一个元素。如果不适用或无效则忽略。

library(dplyr)

df  |>
    mutate(night = rep(c(1:3), each = 3, length.out = n()), .by = site)
#    site night
# 1     1     1
# 2     1     1
# 3     1     1
# 4     1     2
# 5     1     2
# 6     1     2
# 7     2     1
# 8     2     1
# 9     2     1
# 10    2     2
# 11    2     2
# 12    2     2
# 13    2     3
# 14    2     3
# 15    2     3
© www.soinside.com 2019 - 2024. All rights reserved.