ghostpuppy ghostpuppy - 1 month ago 12
R Question

Referencing a data.table column by pattern

I am attempting to plot multiple data tables that share a column name pattern using a function. Below are two sample tables:

dt1 = data.table(date=seq(as.Date("2015/06/20"), as.Date("2015/06/29"), by= "day"),
ppp_min = rnorm(10), ppp_mean = rnorm(10), ppp_max = rnorm(10))
dt2 = data.table(date=seq(as.Date("2015/06/20"), as.Date("2015/06/29"), by= "day"),
qqq_min = rnorm(10), qqq_mean = rnorm(10), qqq_max = rnorm(10))

And a sample plot function:

plt <- function(dt,code) {
min <- paste(code, '_min',sep='')
plot(dt$date, dt[,get(min)])

The function allows to specify the data table to plot. The "code" in the function is used to apply relevant titles and write file names but coincidentally matches the variable in the column names. This is an application of Get columns by string from data.table

My question is: Is it possible to do a pattern match instead? I have tried to do this using
and applying
as suggested in the question pass column name in data.table using variable in R

I have attempted doing something like:

plot(dt$date, dt[,grep("min",names(dt))])

My reasoning for attempting a pattern match is that I have multiple
I am plotting and the first solution seems recursive. In this instance the "code" matches the variable but what if it didn't and I still want to pattern match?



Frank's suggested answer is the most straight forward. It was tested to plot large data tables with a higher level of complexity and worked! The simplified function that works with the sample tables is found below.

plt <- function(dt,code) {
plot(dt$date, dt[[grep("min",names(dt))]])