我正在编写一个R脚本来获取一些数据库数据,然后使用RODBC包进行处理。目前我所有的sqlQuery命令都是一个长字符串;
stsample<-sqlQuery(odcon, paste"select * from bob.DESIGNSAMPLE T1, bob.DESIGNSUBJECTGROUP T2, bob.DESIGNEVENT T3, bob.CONFIGSAMPLETYPES T4 WHERE T1.SUBJECTGROUPID = T2.SUBJECTGROUPID AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY AND T1.STUDYID = T2.STUDYID AND T1.STUDYID = T3.STUDYID AND T1.STUDYID = ", chstudid, sep=""))
head(stsample)
看起来很难看,难以阅读/更新。我已经尝试过将它们设置成多行,但是后来新行字符会受到影响,目前我最好使用大量的粘贴;
stsample<-sqlQuery(odcon,
paste(
"select ",
"* ",
"from ",
"BOB.DESIGNSAMPLE T1, ",
"BOB.DESIGNSUBJECTGROUP T2, ",
"BOB.DESIGNEVENT T3, ",
"BOB.CONFIGSAMPLETYPES T4 ",
"WHERE ",
"T1.SUBJECTGROUPID = T2.SUBJECTGROUPID ",
"AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID ",
"AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY ",
"AND T1.STUDYID = T2.STUDYID ",
"AND T1.STUDYID = T3.STUDYID ",
"AND T1.STUDYID = ",chstudid,
sep="")
)
head(stsample)
但是我不喜欢在每条线上放置引号,并且让我的空白正确。还有更好的方法吗?
答案 0 :(得分:6)
我会用这样的东西:
stsample<-sqlQuery(odcon,
paste("
####DATASET CONSTRUCTION QUERY #########
select
*
from
BOB.DESIGNSAMPLE T1,
BOB.DESIGNSUBJECTGROUP T2,
BOB.DESIGNEVENT T3,
BOB.CONFIGSAMPLETYPES T4
WHERE
T1.SUBJECTGROUPID = T2.SUBJECTGROUPID
AND T1.TREATMENTEVENTID = T3.TREATMENTEVENTID
AND T1.SAMPLETYPEKEY = T4.SAMPLETYPEKEY
AND T1.STUDYID = T2.STUDYID
AND T1.STUDYID = T3.STUDYID
AND T1.STUDYID =
###################################
", as.character(chstudid), sep="")
)
答案 1 :(得分:2)
如何使用gsub(“\ n”,“”,“长多行选择字符串”)而不是粘贴?
答案 2 :(得分:0)
这是一个非常老的问题,但认为这可能对某人有用。
我发现有用的一件事是GetoptLong软件包,它提供了qq()函数。我认为它是受Perl启发的,但从本质上讲,它提供了一种通过简单的变量插值来制作多行字符串的方法。例如:
library(GetoptLong)
tableName <- "myTable"
id <- 42
sqlQuery(odcon, qq("
SELECT * FROM @{tableName}
WHERE id = @{id}
LIMIT 1
")
很明显,我应该提一下通常的警告,如果您直接使用用户输入,这是个坏主意,在这种情况下最好使用某种准备好的语句。