采用以下示例函数
temp_fn <- function(){
print("hello world")
}
我知道键入不带括号的函数名将返回函数定义,即:
> temp_fn
function(){
print("hello world")
}
但是,我无法弄清楚如何将打印出来的内容存储到角色对象中。例如
> store_temp_fn <- as.character(temp_fn)
Error in as.character(temp_fn) :
cannot coerce type 'closure' to vector of type 'character'
答案 0 :(得分:2)
您可以将capture.output()
与功能名称结合使用,如下所示:
temp_fn <- function(){
print("hello world")
}
temp_fn_string <- cat(paste(capture.output(temp_fn), collapse = "\n"))
> temp_fn_string
function(){
print("hello world")
}>
答案 1 :(得分:2)
以下是另一个建议:
out <- as.character(getAnywhere(temp_fn)$objs)[[1]]
> out
#[1] "function () \n{\n print(\"hello world\")\n}"
> cat(out)
#function ()
#{
# print("hello world")
#}
答案 2 :(得分:2)
paste(deparse(yourFunction), collapse="\n")
或者
dput(yourFunction, "yourfile.R")
如果你想把它作为一个大字符串。
或者,如果要将其保存到文件
public class NewServlet extends HttpServlet {
//[...]
protected void doGet(
//[...]
try {
DAO ldapdao = new DAO();
List<Entry> entries = null;
switch (enumPage.fromString(operation)) {
// [...]
case add:
String values[] = request.getParameterValues("item");
try {
ldapdao.addentry(values);
link = "entryadded.jsp";
} catch (Exception exp) { // 2
throw new MyException("Entry Not Added");
}
break;
case remove:
entries = ldapdao.searchEntry(request.getParameter("item"));
if (entries.isEmpty()) {
throw new MyException("Entry Not Removed"); //3
} else {
ldapdao.remove(request.getParameter("item"));
link = "entryremoved.jsp";
}
break;
case modified:
String values1[] = request.getParameterValues("item");
try {
ldapdao.modify(values1);
link = ("modified.jsp");
} catch (Exception exp) { //4
throw new MyException("Entry Not Modified");
}
// [...]