编程R循环

programming R loop

我需要 R 编程方面的帮助。我有 data.frame B 一列

x<- c("300","300","300","400","400","400","500","500","500"....etc.)  **2 milion rows** 

我需要用 运行k 创建下一列。下一列应显示为

y<- c(1,2,3,1,2,3,1,2,3,......etc. ) 

我使用了 cycle with for

B$y[1]=1
for (i in 2:length(B$x))
{  
     B$y[i]<-ifelse(B$x[i]==B$x[i-1], B$y[i-1]+1, 1)
}

过程 运行 4 小时。

所以我需要任何加速或其他方面的帮助。
谢谢你的回答。

这是 dplyr 的方法,在 200 万行上大约需要 0.2 秒。

首先我制作示例数据:

n = 2E6  # number of rows in test
library(dplyr)
sample_data <- data.frame(
  x = round(runif(n = n, min = 1, max = 100000), digits = 0)
) %>%
  arrange(x)  # Optional, added to make output clearer so that each x is adjacent to the others that match.

然后我按 x 分组并使 y 显示 x 在该组中出现的 # 次。

sample_data_with_rank <- sample_data %>%
  group_by(x) %>%
  mutate(y = row_number()) %>%
  ungroup()

head(sample_data_with_rank, 20)

# A tibble: 20 x 2
       x     y
   <dbl> <int>
 1     1     1
 2     1     2
 3     1     3
 4     1     4
 5     1     5
 6     1     6
 7     1     7
 8     1     8
 9     1     9
10     1    10
11     1    11
12     1    12
13     1    13
14     1    14
15     1    15
16     2     1
17     2     2
18     2     3
19     2     4
20     2     5

这是一个解决方案,基数 R:

B <- data.frame(x = rep(c(300, 400, 400), sample(c(5:10), 3)))
B
B$y <- ave(B$x, B$x, FUN=seq_along)