lundi 1 février 2021

Fill R datatable upon condition with it's own value

given this data table as an example:

    ID   Type   W     X        Y        Z       D   stderr Zscore  BABA  ABBA  nsnps
1: D14     OG   P1    P2       X1 OUTGROUP  0.0000 0.000000 -4.100     0     0      0
2: D14     OG   P1    P2       X2 OUTGROUP  0.0000 0.000000  7.200     0     0      0
3: D14     OG   P1    P2       X3 OUTGROUP  0.0000 0.000000 -2.000     0     0      0
4: D14    REP   P1    P2       X1 OUTGROUP -0.0281 0.005291 -5.317 46148 48819 869128
5: D14    REP   P1    P2       X2 OUTGROUP  0.0413 0.005276  7.837 43594 40132 751945
6: D14    REP   P1    P2       X3 OUTGROUP -0.0177 0.005773 -3.072 43764 45344 787440
7: D14    EXP   P1    P2       X1 OUTGROUP -0.0226 0.006499 -3.485 44643 46712 835427
8: D14    EXP   P1    P2       X2 OUTGROUP  0.0472 0.006721  7.030 44123 40142 758734
9: D14    EXP   P1    P2       X3 OUTGROUP -0.0173 0.006892 -2.509 45022 46606 809031

I am trying to add a column to all row that have a type different from "OG". In this new column I am trying to put the Zscore from the corresponding row with the "OG" type. Here is the expected output:

    ID   Type   W     X        Y        Z       D   stderr Zscore  BABA  ABBA  nsnps.  Zexpect
1: D14     OG   P1    P2       X1 OUTGROUP  0.0000 0.000000 -4.100     0     0      0  NA
2: D14     OG   P1    P2       X2 OUTGROUP  0.0000 0.000000  7.200     0     0      0  NA
3: D14     OG   P1    P2       X3 OUTGROUP  0.0000 0.000000 -2.000     0     0      0  NA
4: D14    REP   P1    P2       X1 OUTGROUP -0.0281 0.005291 -5.317 46148 48819 869128  -4.100
5: D14    REP   P1    P2       X2 OUTGROUP  0.0413 0.005276  7.837 43594 40132 751945   7.200
6: D14    REP   P1    P2       X3 OUTGROUP -0.0177 0.005773 -3.072 43764 45344 787440  -2.000 
7: D14    EXP   P1    P2       X1 OUTGROUP -0.0226 0.006499 -3.485 44643 46712 835427   -4.100
8: D14    EXP   P1    P2       X2 OUTGROUP  0.0472 0.006721  7.030 44123 40142 758734   7.200
9: D14    EXP   P1    P2       X3 OUTGROUP -0.0173 0.006892 -2.509 45022 46606 809031  -2.000   

If the row with "OG" contain their own ZScore it's not an issue. I tried to do so but without success:

DT[Type!="OG", Zexpect:=Zscore, .("ID","Type")]

Thanks !

Aucun commentaire:

Enregistrer un commentaire