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)])
}
plt(dt1,ppp)
plt(dt2,qqq)
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 grep
and applying eval()
and quote()
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 colnames
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?
Thanks