R 中函数内的函数不起作用
Function within function in R does not work
我定义了以下函数:
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(conn@ptr, statement) :
no such table: input_table
我想这是关于环境的一些问题,但我不明白这一点。非常感谢您的帮助。
我会在你的第一个函数中使用 eval
而不是 deparse
,并将 table 的名称作为字符串传递。这样,您就可以在第一个函数中获取变量 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(conn@ptr, statement) :
no such table: second_table
使用 eval
,您还可以将 table 的名称作为对象传递:
second_table <- "mytable"
select_category_amounts(second_table,"*","Reservas","categoria2")
Error in rsqlite_send_query(conn@ptr, statement) : no such table: mytable
我定义了以下函数:
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(conn@ptr, statement) :
no such table: input_table
我想这是关于环境的一些问题,但我不明白这一点。非常感谢您的帮助。
我会在你的第一个函数中使用 eval
而不是 deparse
,并将 table 的名称作为字符串传递。这样,您就可以在第一个函数中获取变量 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(conn@ptr, statement) :
no such table: second_table
使用 eval
,您还可以将 table 的名称作为对象传递:
second_table <- "mytable"
select_category_amounts(second_table,"*","Reservas","categoria2")
Error in rsqlite_send_query(conn@ptr, statement) : no such table: mytable