使用局部变量更新函数

时间:2018-06-08 21:22:38

标签: r function

如何使用指定变量的值更新函数?这对于更新for循环中的函数非常有用。

t <- 10
fn <- function(x) return(x + t)

拨打

function(x) return(x + t)

所需的输出

function(x) return(x + 10)

尝试

我尝试使用body()expression(),但没有运气。

body(fn) <- expression(x + t)

更新:我应该提到我需要更新功能,以便我可以使用integrate()功能进行集成。

2 个答案:

答案 0 :(得分:0)

我建议改为使用闭包,这是一个返回函数的函数(带有相关环境,在这种情况下找到t):

fn <- function(t) function(x) x + t

fn(10)    
# function(x) x + t
# <bytecode: 0x02aa2a74>
# <environment: 0x177baf80>

fn(10)(32)    
# [1] 42

for循环中使用示例:

for (i in 1:3) print(fn(i)(7))

# [1] 8
# [1] 9
# [1] 10  

答案 1 :(得分:0)

感谢@Rich Scriven,这有效:

> fn
> function (x) 
> return(x + 10)
> fn(1)
> 11

拨打

$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1','Report Date : '.date("F d, Y"));
$objPHPExcel->getActiveSheet()->setCellValue('B3','Starting Episodes : December, 2017 (Month)');
$objPHPExcel->getActiveSheet()->setCellValue('B4','Branches : Branches : Columbia , Concord , Madison , Ogden , Springfield , Unmatched ZipColumbia , Concord , Madison , Ogden , Springfield , Unmatched Zip');

$objPHPExcel->getActiveSheet()->getStyle("B3:H3")->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('B3:H3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->mergeCells('A1:B1');
$objPHPExcel->getActiveSheet()->mergeCells('B3:H3');
$objPHPExcel->getActiveSheet()->mergeCells('B4:H4');

$excel_path =  dirname(__FILE__);   //$_SERVER['DOCUMENT_ROOT']; //dirname(__FILE__);
$save_file_path = $excel_path.'/../../results.xlsx'; 

//echo $save_file_path; die;

ob_clean(); 
//$output=$header."\n".$data;
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//header('Content-Type: application/vnd.ms-excel');
//header("Content-Disposition: attachment; filename=".$name.".xls");
header("Content-Disposition: attachment; filename=\"$name.xlsx\"");
header("Cache-Control: max-age=0");
header('Content-Transfer-Encoding: binary');
header("Expires: 0");
header("Cache-Control: no-cache");
    header("Pragma: no-cache");
//header('Content-Length: ' . strlen($final_data));



//if (function_exists('mb_internal_encoding'))
//mb_internal_encoding($oldEncoding);

$objWriter->save($save_file_path);
$objWriter->save("php://output");
//ob_clean();   
die;