2017-07-31 118 views
0

我已經定義了以下功能:功能不起作用

where_condition_SQL<- 
function(table,selected_columns,where_conditions) { 
    new_table<-sqldf(sprintf("select %s from %s where %s", 
          as.character((selected_columns)), 
          deparse(substitute(table)), 
          as.character((where_conditions)))) 
    return(new_table) } 

    select_category_amounts <- function(
    input_table,selected_columns,category,category_column){ 
    new_table<-where_condition_SQL(input_table, 
      selected_columns=as.character(selected_columns), 
         where_conditions=sprintf("%s='%s'", 
               as.character(category_column), 
               as.character(category)))  return(new_table) } 

當我嘗試運行第二個功能:

select_category_amounts(second_table,"*","Reservas","categoria2") 

那麼它不承認second_table和給我以下錯誤:

Error in rsqlite_send_query([email protected], statement) : 
no such table: input_table 

我想這是關於環境的一些問題,但我沒有得到重點。提前非常感謝您的幫助。

+0

請仔細閱讀[MCVE ]。 –

回答

0

我會在第一個函數中使用eval而不是deparse,並將表名作爲字符串傳遞。這樣一來,就可以得到變量table的內容,你的第一個功能:

where_condition_SQL<- 
    function(table,selected_columns,where_conditions) { 
    new_table<-sqldf(sprintf("select %s from %s where %s", 
          as.character((selected_columns)), 
          eval(table), 
          as.character((where_conditions)))) 
    return(new_table) } 

select_category_amounts("second_table","*","Reservas","categoria2") 
Show Traceback 

Rerun with Debug 
Error in rsqlite_send_query([email protected], statement) : 
    no such table: second_table 

隨着eval,你也可以通過表的名稱作爲一個對象:

second_table <- "mytable" 
select_category_amounts(second_table,"*","Reservas","categoria2") 

Error in rsqlite_send_query([email protected], statement) : no such table: mytable 
+0

非常感謝你!有效! – Patricio