Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in R language

I am wondering how assignment works in the R language.

Consider the following R shell session:

> x <- c(5, 6, 7)
> x[1] <- 10
> x
[1] 10 6 7
>

which I totally understand. The vector (5, 6, 7) is created and bound to the symbol 'x'. Later, 'x' is rebound to the new vector (10, 6, 7) because vectors are immutable data structures.

But what happens here:

> c(4, 5, 6)[1] <- 10
Error in c(4, 5, 6)[1] <- 10 :
  target of assignment expands to non-language object
>

or here:

> f <- function() c(4, 5, 6)
> f()[1] <- 10
Error in f()[1] <- 10 : invalid (NULL) left side of assignment
>

It seems to me that one can only assign values to named data structures (like 'x').

The reason why I am asking is because I try to implement the R language core and I am unsure how to deal with such assignments.

Thanks in advance

like image 403
Sven Hager Avatar asked May 23 '12 12:05

Sven Hager


People also ask

What is an assignment in R?

The assignment operator is used to assign a value. For instance we can assign the value 3 to the variable x using the <- assignment operator. We can then evaluate the variable by simply typing x at the command line which will return the value of x .

Can you use for assignment in R?

The Google R style guide prohibits the use of “=” for assignment. Hadley Wickham's style guide recommends “<-” If you want your code to be compatible with S-plus you should use “<-”

How do I write an assignment operator in R?

In RStudio the keyboard shortcut for the assignment operator <- is Alt + - (Windows) or Option + - (Mac).


2 Answers

It seems to me that one can only assign values to named data structures (like 'x').

That's precisely what the documentation for ?"<-" says:

Description:

 Assign a value to a name.

x[1] <- 10 doesn't use the same function as x <- c(5, 6, 7). The former calls [<- while the latter calls <-.

like image 158
Joshua Ulrich Avatar answered Oct 24 '22 23:10

Joshua Ulrich


As per @Owen's answer to this question, x[1] <- 10 is really doing two things. It is calling the [<- function, and it is assigning the result of that call to x.

So what you want to achieve your c(4, 5, 6)[1] <- 10 result is:

> `[<-`(c(4, 5, 6),1, 10)
[1] 10  5  6
like image 25
Ari B. Friedman Avatar answered Oct 24 '22 23:10

Ari B. Friedman