【问题标题】:Issue with Creating Function in R在 R 中创建函数的问题
【发布时间】:2019-02-08 19:55:24
【问题描述】:

我在 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 将我的论点解释为列吗?

【问题讨论】:

    标签: r function arguments


    【解决方案1】:

    您不能像这样在 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)
    

    【讨论】:

      【解决方案2】:

      在字符串中,"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"
      

      【讨论】:

        猜你喜欢
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-08
        • 2021-02-16
        • 2021-10-14
        • 1970-01-01
        • 2020-05-02
        相关资源
        最近更新 更多