Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `for` a function in R?

Tags:

r

At page 307 of Norman Matloff's The Art of R Programming, the author says

for() is, in fact, a function.

The context is to give a remark on a piece of code snippet

for (i in 1:length(x)) z[i] <- x[i] + y[i]

The author comments

Though syntactically the loop looks innocuous, for() is, in fact, a function.

My understanding is that what he is saying is that for() is a function much like + is a function (callable object). Say we may call + in a standard function calling way like

"+"(3 ,5)  # 8

I have background in C/C++ and Python and I have noticed several subtle differences between the languages. For example,

  • return is a function, not a statement, in R, so that we must write return(1) with the parentheses.

Going back to my question: is for a function in R?

Thanks for any clarification.

like image 606
aafulei Avatar asked May 19 '19 07:05

aafulei


People also ask

Is for loop a function in R?

For loop in R Programming Language is useful to iterate over the elements of a list, dataframe, vector, matrix, or any other object. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object.

What does %>% mean in Dplyr?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

What types of functions are used in R?

There are mainly three types of function in R programming: Primitive Functions. Infix Functions. Replacement Functions.

What is any function in R?

The any function in R will tell if you if there are ANY of the given search terms in your vector. It returns either TRUE or FALSE. To demonstrate this function, let's create a quick vector that goes from -3 to 5, incrementing by 1.


1 Answers

for is a function, but the symbol for is also recognised by the parser as part of the convenient syntax that we can use to call the function for. These are two different things conveniently named the same (note that in is not a function).

is.function(`for`)
#> [1] TRUE

x <- y <- z <- 1:3
for (i in 1:length(x)) z[i] <- x[i] + y[i]
z
#> [1] 2 4 6

x <- y <- z <- 1:3
`for`(i, 1:length(x), z[i] <- x[i] + y[i])
z
#> [1] 2 4 6

Created on 2019-05-19 by the reprex package (v0.2.1)

In a similar fashion the if (cond) foo else bar syntax maps to the function call `if`(cond, foo, bar), but there is no else function.

All other control flow constructs (see ?Control) are also functions.

like image 130
Moody_Mudskipper Avatar answered Oct 13 '22 01:10

Moody_Mudskipper