0

I'm trying to write a code snippet that will allow others to copy and paste it with minimal changes. There is a variable name that will be different every time, so I would like the other users to be able to assign the variable name to a variable at the head and then I will reference that variable using get() or assign(). This variable will be a data frame. For instance:

name_of_frame <- "number_one"
# This is where they will name the variable

assign (name_of_frame, read.csv("....", header=FALSE))

new_variable <- get(name_of_frame) [2:nrow(get(name_of_frame)),]

These work fine. The one that doesn't is this:

colnames(get(name_of_frame)) <- new_vector

This throws the error: Error in colnames(get(name_of_frame)) <- new_vector : could not find function "get<-"

If I substitute this it works fine:

colnames(number_one) <- new_vector 

Why is this the only context where I can't use get(name of variable) to substitute for the variable?

leviemb
  • 49
  • 6
  • why's `<=` in 1st line? – Aman J Aug 07 '20 at 19:54
  • 1
    If you replace the `<=` with `<-` the code you posted works fine for me. The error message you quote does not seem to be consistent with the code that is just above - are you sure it's that error for exactly that function? – Moritz Schwarz Aug 07 '20 at 19:55
  • Generally using [get/assign is not advisable](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). Often there are more R-like ways to do things. You cannot use special functions like `colnames<-` with the results from `get()` because you are not passing in the symbol to be updated. `get()` returns a data.frame. Its the same as calling `colnames(data.frame(x=1)) <- c("hello")` which doesn't work either. – MrFlick Aug 07 '20 at 20:10
  • Sorry, I had to retype my code, but the original has <- and it still doesn't work. I'm puzzled why it works for @MoritzSchwarz? – leviemb Aug 10 '20 at 15:26
  • It looks like this has been closed, I will try to re-ask in a clearer way. – leviemb Aug 10 '20 at 16:04

0 Answers0