Referencing the data.table column using a template

I am trying to build multiple data tables that use the 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 an example graph 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 you to specify a data table to build. The "code" in the function is used to apply appropriate titles and write filenames but match the variable in the column names. This app Get columns by row from data.table

My question is, is pattern matching possible? I tried to do it with grep

and applying eval()

and quote()

as suggested in the question pass the column name to data.table using a variable in R

I tried to do something like:

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

      

My reasoning about trying pattern matching is that I have several colnames

I am drawing and the first solution seems to be recursive. In this case, "code" matches a variable, but what if it doesn't and I still want to match a pattern?

thank

+2


source to share


2 answers


Frank offered the most direct answer. It has been tested to build large data tables with a higher level of complexity and it works! A simplified function that works with example tables is shown below.



plt <- function(dt,code) {
plot(dt$date, dt[[grep("min",names(dt))]])
}
plt(dt1,ppp)
plt(dt2,qqq)

      

+1


source


Using data tables A function %like%

will provide you with what you want without having to create a function. There are several options depending on what you are looking for:



plot(dt1[,.SD, .SDcols=names(dt1) %like% "date|_min$"])

dt1[,lapply(.SD, plot, date), .SDcols=names(dt1) %like% "_min$"]

code <- c("ppp", "qqq")
plot(dt1[,.SD, .SDcols=names(dt1) %like% sprintf("date|(%s)_min$", paste(code, collapse="|"))])

      

0


source







All Articles