【问题标题】:Outside of format, should toString ever be used?在格式之外,应该使用 toString 吗?
【发布时间】:2020-10-06 19:50:40
【问题描述】:

The very first line of the documentation for toString 明确将其称为格式化函数的辅助函数。这是否表明它不应该在格式函数的内部代码之外使用?如果是这样,为什么 R 将其留给 userR 使用?

【问题讨论】:

  • 我用过它,这里有很多很多例子,见123

标签: r string coercion


【解决方案1】:

您实际上是在问两个问题:

  1. 应该在format之外使用toString吗?
  2. 为什么 R 的用户可以使用它?

关于 1.,请参阅 @Rui Barradas 评论,您可以在 format 之外使用它,并且显然有用例。这也回答了 2.,但实际上还有第二个原因,帮助中也有说明:

这是一个可以为其编写方法的通用函数:这里只描述了默认方法。

这意味着用户可以访问它,以便他们可以轻松地扩展它。例如。说您对矩阵对象的toString.default 的功能不满意:

test_matrix <- matrix(1:4, ncol = 2)
test_matrix
     [,1] [,2]
[1,]    1    3
[2,]    2    4

toString(test_matrix)
[1] "1, 2, 3, 4"

它按列操作,但您希望能够选择是按行还是按列操作。现在您可以通过为矩阵对象编写新的 S3 方法来轻松扩展它:

toString.matrix <- function(x, width = NULL, rowwise = TRUE) {
  if (rowwise) {
    marg <- 1
  } else {
    marg <- 2
  }
  temp <- apply(x, marg, paste, collapse = ", ")
  string <- paste(temp, collapse = ", ")
  
  if (missing(width) || is.null(width) || width == 0) 
    return(string)
  if (width < 0) 
    stop("'width' must be positive")
  if (nchar(string, type = "w") > width) {
    width <- max(6, width)
    string <- paste0(strtrim(string, width - 4), "....")
  }
  string
}

toString(test_matrix)
[1] "1, 3, 2, 4"

toString(test_matrix, rowwise = FALSE)
[1] "1, 2, 3, 4"

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2014-12-20
    相关资源
    最近更新 更多