r - Create string with variable names and values for data.table lookup -
i'm trying construct lookup string match values in r data.table. have data.table called mydatatable columns v1:v4 , list called mylist 3 elements c("a", "b", "c"). here's (admittedly inelegant) code:
# create first value matchstr <- paste('v1', '=="', mylist[1], '"', sep="") # construct rest of match string (i in 2:length(mylist)) { matchstr <- paste(matchstr, ' & v', i, '=="', mylist[i], '"', sep="") } matchstr <- paste(matchstr, ",", sep="")
my match string looks this:
matchstr [1] "v1==\"a\" & v2==\"b\" & v3==\"c\","
if use cat output string, looks this:
cat(matchstr) v1=="a" & v2=="b" & v3=="c",
i want use lookup string data.table, this:
mydatatable[v1=="a" & v2=="b" & v3=="c",]
if text shown, result expect. if try this:
mydatatable[matchstr]
i get
error in `[.data.table`(wordtable, matchstr) : when data.table (or character vector), x must keyed (i.e. sorted, and, marked sorted) data.table knows columns join , take advantage of x being sorted. call setkey(x,...) first, see ?setkey.
if try
mydatatable[cat(matchstr)]
i get
v1=="a" & v2=="b" & v3=="c",null data.table (0 rows , 0 cols)
how can work, preferably without awkward string manipulation. thanks!
this horrible way go this, can done:
txt <- "v1==\"a\" & v2==\"b\" & v3==\"c\"" # note - i've removed last comma end of string # example data: set.seed(13) dt <- data.table(replicate(3,sample(letters[1:3],5,replace=true))) dt # v1 v2 v3 #1: c b #2: b c #3: b c c #4: c b #5: c b dt[eval(parse(text=txt))] # v1 v2 v3 #1: b c
keep in mind:
library(fortunes) fortune(106)
if answer parse() should rethink question.
-- thomas lumley r-help (february 2005)
as @arun notes, preferred way use more standard data.table
functionality:
setkey(dt,v1,v2,v3) mylist <- list("a", "b", "c") dt[mylist] # v1 v2 v3 #1: b c
Comments
Post a Comment