简体   繁体   English

R中的Custom .Primitive函数

[英]Custom .Primitive function in R

I known *+* <- function(x,y){ x + y} in R. 我在R中知道*+* <- function(x,y){ x + y}

But if I want to write a function like .print . 但是,如果我想编写类似.print的函数。

And I can show print(iris) with using iris.print . 我可以使用iris.print显示print(iris)

How do I custom my function in R? 如何在R中自定义函数?

The simplest way is to use R's R3 classes. 最简单的方法是使用R的R3类。

A simple example. 一个简单的例子。 Assume we have a new data type --- a vector which we would like to print as a comma-separated string. 假设我们有一个新的数据类型---一个向量,我们希望将其打印为逗号分隔的字符串。

x <- c(1, 2, 3)
# Assign a class attribute. The first element is the class of the object;
# the second element is the parent class
class(x) <- c("Foo", "numeric")
# Define the print method
print.Foo <- function(x) {
  cat(paste(x, collapse = ", "), "\n")
}
# The method is called just like this
print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM