![](/img/trans.png)
[英]Using R, in a function how to reference one or more functions by either the fn.name (as a string) or the fn.obj?
[英]How to reference the string of a function name in R?
hello = function(day){
print day
print "was a good day"
}
func = hello
func("Monday")
print(func) #Want it to print "hello"
我試圖讓print(func)
打印文字字符串“hello”,但仍然讓func("Monday")
在我的代碼的其他部分工作。 是否有可能做到這一點? 如何將 func 指定為文字“hello”?
我試過了
as.character(func)
deparse (func)
但無濟於事。 有任何想法嗎? 謝謝
你可以這樣做:
as.character(quote(hello))
但是 func 不再與名稱 hello 相關聯。 hello 函數的內容會被傳輸,但名稱 hello 不會被傳輸。 所以你不能使用 func 來恢復 hello 字符串。
編輯:實際上我錯了。 見弗蘭克的評論。 你可以這樣做:
hello = function(x) sprintf("%s was a good day",x)
func = function(x) hello(x);
as.character(body(func)[[1]])
而不是func <- hello
,你想要func <- "hello"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.