重复序列 R

Repeating sequence R

我正在尝试使用以下内容在我的数据框的行中重复序列 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)

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

使用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

您可以使用模运算。

这里有两个使用 data.tabledplyr

的实现
## data.table
library(data.table)

setDT( df )[, w := (.I - 1 ) %% 3][]
## .I is what data.table uses to store 'row number'
## think of it as the row 'index'

#    x y w
# 1: 1 1 0
# 2: 2 2 1
# 3: 3 3 2
# 4: 4 4 0
# 5: 5 5 1
# 6: 6 6 2
# 7: 7 7 0

## dplyr
library(dplyr)

df %>%
  mutate(w = (row_number() - 1) %% 3)

#   x y w
# 1 1 1 0
# 2 2 2 1
# 3 3 3 2
# 4 4 4 0
# 5 5 5 1
# 6 6 6 2
# 7 7 7 0

对于0, 1,序列使用 %% 2

使用 base R,我们可以像下面那样使用 %%(但最有效的解决方案是

df$W <- (seq(nrow(df))-1)%%3