如何让嵌套 for 循环中的第二个索引在数据 table 中工作

How can I get the second index within a nested for loop to work in a data table

所以我有一个 data.table,我需要根据列的索引填写值,然后还根据占位符字符填写值。示例:

       V1   V2   V3    V4
Row1   1    1    a     d     
Row2   1    1    a     d
Row3   1    1    a     d
Row4   1    2    a     h
Row5   1    2    a     h
Row6   1    2    a     h
Row7   2    1    b     i
Row8   2    1    b     i
Row9   2    1    b     i
Row10  2    2    b     t
Row11  2    2    b     t
Row12  2    2    b     t

....
Row350k   ...

我需要弄清楚的是如何编写一个 for 循环,其中包含沿第 1 列索引滑动的引用赋值语句。基本上

对于每个列索引,一次一个:

对于 Col1 和 Col2 的每个增量值,依此类推。实际上,第二个索引有 20 多行而不是 2 行。

所需的输出是:

    Col1  Col2   Col3     Col4
Row1   1    1    0.00551    d     
Row2   1    1    0.00551    d
Row3   1    1    0.00551    d
Row4   1    2    0.00553    h
Row5   1    2    0.00553    h
Row6   1    2    0.00555    h
Row7   2    1    0.0011     i
Row8   2    1    0.0011     i
Row9   2    1    0.0011     i
Row10  2    2    0.0010     t
Row11  2    2    0.0010     t
Row12  2    2    0.0010     t
....
Row350k   ...

只是不确定如何使用循环执行此操作,因为 col1 中的值重复了一定次数。 Column1 有 300k 以上的值,因此滑动循环需要动态缩放。

这是我尝试过的:

for (i in seq(1, 4000, 1)) 
{for (ii in seq(1, 2, 1)) {
    data.table[V3 == "a" , V3 := 0.0055 + rnorm(1, 0.0055, 0.08)]
    data.table[V3 == "b" , V3 := 0.0055 + rnorm(1, 0.001, 0.01)]
    }}

谢谢!

如果我正确理解您的问题,这可能会有所帮助。

library(data.table)

dt <- data.table(V1 = c(rep(1, 6), rep(2, 6)), 
                 V2 = rep(c(rep(1, 3), rep(2, 3)), 2),
                 V3 = c(rep("a", 6), rep("b", 6)),
                 V4 = c(rep("d", 3), rep("h", 3), rep("i", 3), rep("t", 3)))

# define a catalog to join on V3 which contains the parameters for the random number generation
catalog <- data.table(V3 = c("a", "b"),
                      const = 0.0055,
                      mean = c(0.0055, 0.001),
                      std = c(0.08, 0.01))

# for each value of V3 generate .N (number of observations of the current V3 value) random numbers with the specified parameters
dt[catalog, V5 := i.const + rnorm(.N, i.mean, i.std), on = "V3", by = .EACHI]
dt[, V3 := V5]
dt[, V5 := NULL]

好的,所以我发现我没有正确增加我的计数器。对于第 1 列中有 4000 个场景的 matrix/data table,每个场景在第 2 列中有 11 个重复,我使用了以下内容:

 Col1counter <- 1
 Col2counter <- 1

for(Col1counter in 1:4000) {

  for(col2counter in 1:11) {

     test1[V1 == col1counter & V2 == col2counter &  V3 == "a" ,  V55 := 0.00558 + rnorm(1, 0.00558, 2)]

  col2counter+ 1
    }
Col1counter+ 1}

在条件语句中使用两个索引可确保它准确地爬行。