R data.table when filtering rows

I create a data table in R and set the column to be used as the key. When I try to extract values ​​from a data table; for strings where there are no matches, I return NA values. Usually I do not want this behavior in my search. Example below

library(data.table) 
dt <- data.table('foo'=seq(10),bar=sample(letters,10))
setkey(dt,bar)
dt[sample(letters,5)]


> dt[sample(letters,5)]
   b foo
1: x   4
2: q   2
3: u   8
4: s  NA
5: b  NA
+4
source share
1 answer

To delete lines NA, simply set nomatch=0:

Here is an example (I deleted a random sample so that everyone can have the same results)

library(data.table)
dt = data.table(foo = 1:10, bar = letters[1:10])
setkey(dt, bar)
needed_letters = letters[c(1:8,11,12)] #1 - 8 are available, 11 and 12 are not
dt[J(needed_letters),nomatch=0]

Matt Add-on

Alternatively, if you prefer the nomatch=0default, you can change the default:

options(datatable.nomatch=0)
dt[J(needed_letters)]    # now, no NAs will be returned

You can check all the arguments as follows:

> args(data.table:::`[.data.table`)

function (x, i, j, by, keyby,
    with = TRUE,
    nomatch = getOption("datatable.nomatch"), 
    mult = "all",
    roll = FALSE,
    rollends = if (roll=="nearest") c(TRUE,TRUE)
               else if (roll>=0) c(FALSE, TRUE)
               else c(TRUE,FALSE),
    which = FALSE,
    .SDcols,
    verbose = getOption("datatable.verbose"), 
    allow.cartesian = getOption("datatable.allow.cartesian"), 
    drop = NULL) 

, , getOption, .

+6

All Articles