按模式逐列引用data.table [英] Referencing a data.table column by pattern

查看:77
本文介绍了按模式逐列引用data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用一个函数绘制多个共享列名模式的数据表。下面是两个示例表:

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))

样例函数示例:

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

该功能允许指定要绘制的数据表。函数中的代码用于应用相关标题和写入文件名,但同时与列名中的变量匹配。这是从data.table中按字符串获取列的应用程序

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

我的问题是:是否可以进行模式匹配?我尝试使用 grep 并应用 eval() quote(),如问题使用R中的变量在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

我尝试执行以下操作:

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?

谢谢

推荐答案

弗兰克(Frank)建议的答案最直接。经过测试,可以绘制具有更高复杂度的大型数据表,并且可以正常工作!可以在下面找到与示例表一起使用的简化函数。

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))]])
}
plt(dt1,ppp)
plt(dt2,qqq)

这篇关于按模式逐列引用data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆