在格式之外,应该使用toString吗?

问题描述

The very first line of the documentation for toString显然将其称为格式函数的辅助函数。这是否表明它永远不应在format函数的内部代码之外使用?如果是这样,为什么R保留它对useR可用?

解决方法

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

  1. 是否应在toString之外使用format
  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,")
  
  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,4"

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...