0

I have a data frame, the name of which is wrapped in a variable "my_var". What I am trying to do is to assign a new column names for this data.

What I have tried is:

names(get(my_var)) <- c("Fruits", "Sweets")  
assign(names(get(my_var)),  c("Fruits", "Sweets"))
within (get(my_var), assign(names(get(my_var)),  c("Fruits", "Sweets")))

Neither of this works.

Thanks

MirrG
  • 406
  • 3
  • 10
  • To rename columns: https://stackoverflow.com/questions/7531868/how-to-rename-a-single-column-in-a-data-frame – Rebecca Bennett Dec 02 '19 at 16:15
  • 1
    “the name of which is wrapped in a variable "my_var"” — Why? This is something that’s generally to avoid. *If* you need computed names, use named list items. And then your code works: `names(the_list[[my_var]]) = c('Fruits', 'Sweets')`. – Konrad Rudolph Dec 02 '19 at 16:23
  • I am producing data frames from files on the fly and I need to name the data frames as the file's name – MirrG Dec 02 '19 at 16:29
  • @MirrG In that case, put them into a list as mentioned. Alternatively, if they all have the same data shape, it may make more sense to load them all into the *same* table, via something like purrr’s `map_dfr` function. – Konrad Rudolph Dec 02 '19 at 16:30
  • @MirrG The point is that when creating data frames on the fly, the way to do that is to put them in a named list, so they can be easily referred to using a character variable representing the list element name. Relying on things like `get` and `assign` will often lead to more problems down the road. – joran Dec 02 '19 at 16:30
  • KonradRudolph, joran, thank you. What I am doing is trying to write a function that takes arbitrary .csv, prepare a dataframe and doing some math with it. So I have "function (file) { name=strsplit(file, "\\.")[[1]][1]; df <- read.csv(file, sep=";"); assign(name, df) .... } " . If I understood correctly, I should write "name" in a list and then assign it to data? my_list[1] <- read.csv(file, sep=";") ? – MirrG Dec 02 '19 at 16:43

1 Answers1

1

you can use setnames from the data.table package:

setnames(get(my_var), names(get(my_var)), c('a', 'b'))
Metariat
  • 522
  • 3
  • 16