1

I came across a solution for renaming the column names of a data.frame:

names(data) <- c("new_name", "another_new_name")

Here is an example:

empl <- c("Mike", "Steven") wa <- c(25000, 30000) data <- data.frame(empl, wa) data # now rename the columns of the dataframe names(data) <- c("employee", "wage") data 

Now I am wondering how it is possible to assign a vector to a function-call. The result of names(data) is a vector with chars. And it seems that this vector is not linked in any way to the data.frame.

Can anyone enlighten me what the mechanisms are?

Trying to explain to myself

names(data) <- c("employee", "wage")

Looking at the assignment above:

  • the left hand side names(data) returns a vector with the old column names.
  • does this assignment not assign to a vector? Instead of to a dataframe‘s attribute?
3
  • 1
    A function can take a vector as argument if that is what you meant f1 <- function(data, nm1) setNames(data, nm1); f1(data, c("employee", "wage")) Commented May 5, 2019 at 5:50
  • 1
    It would be better to add what you would like to do using an example function. Commented May 5, 2019 at 5:56
  • 1
    There are only a few functions, which can on the left side of a assignment. The answer from @SirSaleh describes the details of the interpreter related to this. If you are using RStudio you can see during the search for help for the function names: there is a function names<- Commented May 5, 2019 at 6:12

1 Answer 1

2

Nice question I think. This is how R interpreter works, which calls Replacement functions. you can define function function<- to set functionality for replacement.

Let I have this function:

members_of <- function(x){ print(x) } 

I can call it easily:

members = c("foo", "bar", "baz") members_of(members) # output # [1] "foo" "bar" "baz" 

But lets define members_of<- function using back tick character and tmp and value arguments:

`members_of<-` = function(tmp, value){ tmp = value } 

Now I can assign to function call:

members = c("foo", "bar", "baz") # output # [1] "foo" "bar" "baz" # members_of(members) = c("foo2", "bar2", "baz2") # Now values of members will be # members # [1] "foo2" "bar2" "baz2" 
Sign up to request clarification or add additional context in comments.

2 Comments

So if I want to look up the definition of names() function in RStudio, I need to query ?`names<-` ?
if you try to print using that or this print.function(names<-) you get function (x, value) .Primitive("names<-") which means it's probably c compiled code and need to view R source code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.