官术网_书友最值得收藏!

  • Learning Shiny
  • Hernán G. Resnizky
  • 361字
  • 2021-07-09 21:46:10

Object-oriented programming concepts

As in any other object-oriented programming language, a class in R is an abstract definition of an object type with specific attributes associated to it. For instance, for an eventual dog class (which is a general definition of a dog), we could say that it has the color, size, age, and so on attributes.

An object is an instance of a specific class. Continuing with the previous example, we could have a Dog1 object whose attributes can be the following:

  • color: "brown"
  • size: 5.5 inch
  • age: 3 years

In R, the attributes of an object can be accessed by typing attr(object, "attribute"), for instance:

data(iris)
attributes(iris)

In this example, a data frame object (data frame objects will be explained later in this chapter) called iris is loaded, which has the names, row.names, and class attributes (R considers the class of an object an attribute as well). In most cases, many of the values for these attributes in a particular object can be accessed by typing either attr(object, "attribute") or the name of the attribute as follows:

attr(iris,"names")
names(iris)

Normally, the second option will be used.

Finally, functions are usually routines to which a set of values is given (input) and an output is returned. They can be classified in two big groups: the ones that return a value and the ones that don't return a value. For example, save and print functions, among others. A very easy way to distinguish them is by testing whether the output can be assigned to a variable:

> var1 <- sum(c(4,3,2))
> var1
[1] 9

> var1 <- cat(9)
9
> var1
NULL

In the first case, the output of the sum function is assigned to var1. So, when typing the name of the variable, it outputs its value to the console. In the second case, cat just outputs the value to the console but cannot assign this output to a variable. For this reason, var1 is created but no value is assigned to it. So when it is typed, it returns NULL, which means that it has no value associated with it.

In the following example, a function that returns a value is declared:

test.function <- function(a,b,c){
  result <- (a * b) + c
  return(result)
}

In RStudio, whenever a function is declared, it will appear in the Environment section under the Functions section:

Object-oriented programming concepts

The code of a function can be seen when its name is typed without any parentheses:

test.function
## function(a,b,c){
##  result <- (a * b) + c
##  return(result)
## }

Once the function is declared, it is ready to be used:

> test.function(2,3,1)
[1] 7
主站蜘蛛池模板: 慈溪市| 利津县| 会宁县| 广水市| 海伦市| 宜川县| 莲花县| 天祝| 临夏县| 韶山市| 东港市| 牟定县| 新巴尔虎左旗| 舞阳县| 卢龙县| 沈阳市| 屏山县| 通州区| 蕉岭县| 大石桥市| 上蔡县| 聂拉木县| 鸡西市| 包头市| 平阳县| 大安市| 宁德市| 临清市| 绥宁县| 横峰县| 大城县| 栾城县| 观塘区| 深水埗区| 祁连县| 潢川县| 闽侯县| 阳曲县| 紫云| 通渭县| 内乡县|