更新多行连接

时间:2018-03-15 22:02:16

标签: r data.table

问题

在进行更新连接时,public class Menu { static final int MIN_NUMBER = 1; static final int MAX_NUMBER = 8; static int image_number = 1; static boolean exit; public static int forward(int current_number) { if (current_number < MAX_NUMBER) { current_number++; } else if (current_number >= MAX_NUMBER) { current_number = MIN_NUMBER; } return current_number; } public static void showMenu() { int current_number = image_number; // global int that equals 1 while (!exit) { Scanner input = new Scanner(System.in); Random rand = new Random(); int randomvalue = rand.nextInt(MAX_NUMBER) + MIN_NUMBER; // used in another method System.out.println("1. forward"); // menu with options System.out.println("2."); System.out.println("3."); System.out.println("4. Exit"); System.out.println(current_number); int choice = input.nextInt(); switch (choice) { case 1: forward(current_number); break; case 4: exit = true; break; } } } } 表每个键有多行,如何控制返回哪一行?

实施例

在此示例中,update-join返回i

的最后一行
dt2

如何控制它返回第1行,第2行,第n行,而不是默认为最后一行?

参考

用户@Frank

与此类似的一些引用

2 个答案:

答案 0 :(得分:6)

  

如何控制它返回第1行,第2行,第n行,而不是默认为最后一行?

不优雅,但有点工作:

n = 3L
dt1[, v := dt2[.SD, on=.(id), x.letter[n], by=.EACHI]$V1]

一些问题:

  1. 它没有选择使用GForce,例如,如下所示:

    > dt2[, letter[3], by=id, verbose=TRUE]
    Detected that j uses these columns: letter 
    Finding groups using forderv ... 0.020sec 
    Finding group sizes from the positions (can be avoided to save RAM) ... 0.000sec 
    lapply optimization is on, j unchanged as 'letter[3]'
    GForce optimized j to '`g[`(letter, 3)'
    Making each group and running j (GForce TRUE) ... 0.000sec 
       id V1
    1:  1  c
    
  2. 对于某些加入的群组,如果n超出1:.N,则不会发出警告:

    n = 40L
    dt1[, v := dt2[.SD, on=.(id), x.letter[n], by=.EACHI]$V1]
    
  3. 或者,养成检查更新联接i中的x[i]是否已被加入列“锁定”的习惯:

    cols = "id"
    stopifnot(nrow(dt2) == uniqueN(dt2, by=cols))
    

    然后根据需要创建一个不同的i表来加入

    mDT = dt2[, .(letter = letter[3L]), by=id]
    dt1[mDT, on=cols, v := i.letter]
    

答案 1 :(得分:6)

我能想到的最灵活的想法是只加入包含所需行的dt2部分。所以,对于第二行:

dt1[ 
    dt2[, .SD[2], by=id]
    , on = "id" 
    , letter := i.letter
    ]

dt1
#   id letter
#1:  1      b

使用@Frank的帽子提示来简化dt2的子选择。