替换R中的文本文件中的字符串

时间:2014-07-16 03:03:25

标签: r

如果我读入R中的文本文件,我想根据某种模式替换该文本文件中的字符串。例如,创建一个函数调用它:replace(query,pattern,param),它基本上搜索整个查询并将任何出现的模式替换为param。 例如,

输入文件

select * FROM 
from Meds_EDW
 WHERE Meds_EDW.Medication_Start_Date < to_date('pattern', 'MM/DD/YYYY')

然后在R中会有一个函数读取此输入文件并替换&#39;模式&#39;约会。

我想运行某种循环来运行这个sql输入文件多个日期。

1 个答案:

答案 0 :(得分:3)

您可能正在寻找sprintf(...)

template <- "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('%s', 'MM/DD/YYYY')"
query <- sprintf(template, "01/01/2014")
query
# [1] "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('01/01/2014', 'MM/DD/YYYY')"

dates   <- c("01/01/2014","02/01/2014","03/01/2014")
for (date in dates) print(sprintf(template,date))
# [1] "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('01/01/2014', 'MM/DD/YYYY')"
# [1] "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('02/01/2014', 'MM/DD/YYYY')"
# [1] "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('03/01/2014', 'MM/DD/YYYY')"

请注意使用%s作为字符串的占位符。有关其他选项,请参阅文档。

如果您已经使用sqldf(加载gsubfn),那么这也会有效:

library(sqldf)
template <- "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('$date.var', 'MM/DD/YYYY')"
date.var <- "01/01/2014"
fn$identity(template)
# [1] "select * FROM from Meds_EDW WHERE Meds_EDW.Medication_Start_Date < to_date('01/01/2014', 'MM/DD/YYYY')"