在R中创建函数的问题

时间:2019-02-08 19:55:24

标签: r function arguments

R在识别函数中的参数时遇到问题。我正在尝试获取两个数据帧并比较公共列的内容。以下是我的代码:

install.packages("rowr")
library(rowr)

Check=function(zzz){
Newcheck=sqldf("select Office, Station
                           from new
                            where Office=zzz
                             group by Office, Station")   
Oldcheck=sqldf("select Office, Station
                             from old
                             where Office=zzz
                             group by Office, Station")  
check_old_v_new=cbind.fill(Newcheck,Oldcheck,fill=NA)   
return(check_old_v_new) }

Check(6)

每当我运行最后一行代码时,都会收到以下消息:result_create(conn @ ptr,statement)中的错误:没有这样的列:zzz

我知道zzz不是一列。这是我函数中的参数。有人可以帮我确定为什么R将我的论点解释为一列吗?

2 个答案:

答案 0 :(得分:0)

在字符串中,"zzz"仅3个字母。例如,如果我设置了变量i = 55,我不希望R将"this string"解释为"th55s str55ng"-实际上,那太糟糕了。

因此,如果希望R使用存储在另一个字符串中的变量中的字符串,则需要构造该字符串。 pastesprintf就是很好的功能,例如:

> zzz = 6
> paste("select * from old where office =", zzz, "group by station")
[1] "select * from old where office = 6 group by station"

paste只是把东西粘在一起。 sprintf使用“空白填充”方法,对于SQL查询等而言,这种方法更具可读性:

> sprintf("select * from old where office = %s group by station", zzz)
[1] "select * from old where office = 6 group by station"

答案 1 :(得分:0)

您不能像这样在sqldf语句中传递变量。您的代码将zzz作为该列中的值。您可以在这里使用sprintf。

install.packages("rowr")
library(rowr)

Check=function(zzz){
Newcheck=sqldf(sprintf("select Office, Station
                       from new
                        where Office='%s'
                         group by Office, Station",zzz))   

Oldcheck=sqldf(sprintf("select Office, Station
                         from old
                         where Office='%s'
                         group by Office, Station",zzz))

check_old_v_new=cbind.fill(Newcheck,Oldcheck,fill=NA)   
return(check_old_v_new) }

Check(6)