簡體   English   中英

在函數結果中抑制attr()的輸出

[英]Suppress output from attr() in function result

data.frame的源代碼中,最后三行代碼設置屬性並返回結果。

    ...
    attr(value, "row.names") <- row.names
    attr(value, "class") <- "data.frame"
    value
}

在我寫的函數中,結果是lapply創建的命名列表。 在我在函數體中設置任何屬性之前,結果如下。

> x <- data.frame(a = 1:5, b = letters[1:5])    
> (g <- grep.dataframe("a|c", x))
# ...    
# $b
#   value row
# 1     a   1
# 2     c   3
> attributes(g)  # I want "list" in here...
# $names
# [1] "a" "b"

我想“類”被包含在屬性列表,所以我加attr(res, "class") <- "list"res之前是最終結果) res “class”現在顯示在屬性列表中。 但是,它也打印出函數的結果,這是我不想要的。 我嘗試用invisible包裹它,但那不起作用。

為什么手動分配的屬性使用函數結果打印,但在我創建的新數據框中被抑制?

> (h <- grep.dataframe("a|c", x))
# ...    
# $b
#   value row
# 1     a   1
# 2     c   3

# attr(,"class")  # ...This prints with the result. I don't want that.
# [1] "list"
> attributes(h)   # ...But I want these attributes
# $names
# [1] "a" "b"

# $class
# [1] "list"

?class文檔提供了一些指示:

許多R對象都有一個class屬性,一個字符向量給出了對象繼承的類的名稱。 如果對象沒有類屬性,則它具有隱式類“矩陣”,“數組”或模式(x)的結果(除了整數向量具有隱式類“整數”)。 (函數oldClass和oldClass < - 獲取並設置屬性,也可以直接完成。)

當將通用函數fun應用於具有類屬性c(“first”,“second”)的對象時,系統將搜索名為fun.first的函數,如果找到它,則將其應用於對象。 如果沒有找到這樣的函數,則嘗試一個名為fun.second的函數。 如果沒有類名生成合適的函數,則使用函數fun.default(如果存在)。 如果沒有class屬性,則嘗試隱式類,然后使用默認方法。

從那以及運行一些簡單的測試,我收集到:

  • 列表是這些隱式類之一 :請參閱attributes(list(1))typeof(list(1))
  • 當在列表上調用print時,它使用print.default
  • print.default打印對象的屬性

所以你可以定義一個print.list來處理你的特殊情況:

 print.list <- function(x, ...) {
    if (is.list(x)) attr(x, "class") <- NULL
    print.default(x, ...)
 }

res <- list(1)
attr(res, "class") <- "list"
res
# [[1]]
# [1] 1

attributes(res)
# $class
# [1] "list"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM