moman822 moman822 - 1 month ago 10
R Question

Why does this happen when assigning names in a function?

Doing this:

x <- data.frame(a=1, b=2, c=3)

func <- function(df) {
names(df) <- c("name1","name2","name3")
}

x<-func(x)


Turns
x
into the character vector of the names

but

doing this:

x <- data.frame(a=1, b=2, c=3)

func <- function(df) {
names(df) <- c("name1","name2","name3")
setDT(df)
}

x<-func(x)


Gives x back as a data.table. It works the same with
as.data.frame(x)
too.

Why does this happen?

Answer

What is returned from the function is the last evaluated expression : c("name1","name2","name3")in the first function, setDT(df) in the second.

To update the names of the data.frame passed as an argument, just return it after update:

x <- data.frame(a=1, b=2, c=3)

func <- function(df) {
  names(df) <- c("name1","name2","name3")
  df # This line returns the data.frame
}

x<-func(x)