I am trying to use the data.table index to perform a fast lookup.
table = c("AX-11415458", "AX-11417054", "AX-11419082", "AX-11421703",
"AX-11422856", "AX-11422870")
df1 = structure(list(V1 = c(26L, 26L, 26L, 26L, 26L, 26L), V2 = c("AX-11415458",
"AX-11417054", "AX-11419082", "AX-11421703", "AX-11422856", "AX-11422870"
), V3 = c(0L, 0L, 0L, 0L, 0L, 0L), V4 = c(705L, 3973L, 2859L,
1683L, 6482L, 11930L), V5 = c("C", "G", "C", "A", "C", "G"),
V6 = c("A", "A", "T", "G", "T", "T")), row.names = c(NA,
-6L), class = "data.frame")
df2=structure(list(V1 = c("MT", "MT", "MT", "MT", "MT", "MT"), V2 = c("AX-11415458",
"AX-11417054", "AX-11419082", "AX-11421703", "AX-11422856", "AX-11422870"
), V3 = c(0L, 0L, 0L, 0L, 0L, 0L), V4 = c(705L, 3973L, 2859L,
1683L, 6482L, 11930L), V5 = c(".", ".", ".", ".", ".", "."),
V6 = c("A", "A", "T", "G", "T", "T")), row.names = c(NA,
-6L), class = "data.frame")
setDT(df1)
setDT(df2)
setkey(df1, V2)
setkey(df2, V2)
I would like to iterate over table and lookup the value in both df1 and df2 and replace V5 and V6 in df2 with those in df1.
for (i in table) {
df2[.(i), nomatch = 0L][,5:6] = df1[.(i), nomatch = 0L][,5:6]
}
But I get the error:
Error in
[<-.data.table
(*tmp*
, .(i), nomatch = 0L, value = list(V1 = "MT", : unused argument (nomatch = 0)
Why can't I do this and is there a correct way to do what I want?
In fact, yours can be directly corrected as
for (i in table) {
df2[i,5:6] <- df1[i,5:6]
}
nomatch = 0L
is only used for inner join and the chain [,5:6]
will not update the data in original df
.
In addition, You can also try this method
setDT(df1)
setDT(df2)
df3 <- df1[V2 %chin% table]
setkey(df2,V2)
setkey(df3,V2)
df2[,`:=`(
V5=fcoalesce(df3[df2,V5]),
V6=fcoalesce(df3[df2,V6])
)
]
Result
> df2
V1 V2 V3 V4 V5 V6
1: MT AX-11415458 0 705 C A
2: MT AX-11417054 0 3973 G A
3: MT AX-11419082 0 2859 C T
4: MT AX-11421703 0 1683 A G
5: MT AX-11422856 0 6482 C T
6: MT AX-11422870 0 11930 G T
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.