我怎样才能内嵌套获得第二个指数环在数据表工作

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

所以我有一个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   ...

我需要弄清楚是怎么写的与沿列1的指数滑动参考语句分配的for循环。基本上

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

  • 对于每个V1 = 1V2 = 1替换字符 'a' 与0.0055 + RNORM(1,0.0055,0.08)一次迭代。
  • 对于每个V1 = 1V2 = 2替换字符 'a' 与0.0055 + RNORM(1,0.0055,0.08)一次迭代。 (相同的变化,但与RNORM的另一迭代)
  • 对于每个V1 = 2V1 = 1,用0.0055 + RNORM一次迭代替换字符 'B'(1,0.01)
  • 对于每个V1 = 2V1 = 1,用0.0055 + RNORM(1,0.01)一次迭代(相同的变化,但与RNORM的另一次迭代)替换字符“b”。

等了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的值被重复了一定NUM如何与一个循环做到这一点。列1具有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)]
    }}

谢谢!

r loops data.table increment
2个回答
1
投票

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

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]

0
投票

好了,所以我想通了,我是不正确递增我的柜台。对于在第一列4000级的场景的每个与所述第二柱11次重复一个矩阵/数据表我用follwing:

 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}

在条件语句中使用这两个指数可以确保它通过行准确抓取。

© www.soinside.com 2019 - 2024. All rights reserved.