重复序列R

Sam*_*ick 3 r sequence

我正在尝试使用以下内容在我的数据框的行中重复序列 0、1、2:

x <- c(1, 2, 3, 4, 5, 6, 7)
y <- c(1, 2, 3, 4, 5, 6, 7)

df <- cbind(x, y)
df <- as.data.frame(df)

df$W <- rep(0:2, nrow(df)/3)
df$W <- rep(0:1, nrow(df)/2)

Run Code Online (Sandbox Code Playgroud)

这不起作用,因为替换有 6 行,数据有 7。我觉得必须有一个更简单的解决方案。我只希望它开始下一个序列,但在数据帧的最后一行结束时停止。所以W只会是 0, 1, 2, 0, 1, 2, 0. 对于另一个选项,rep(0:1)它将是 0, 1, 0, 1, 0, 1, 0

akr*_*run 5

使用length.out选项

rep(0:2, length.out = nrow(df))
#[1] 0 1 2 0 1 2 0
rep(0:1, length.out = nrow(df))
#[1] 0 1 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)