1

Could anyone explain the behavior below?

df <- data.frame(dog = 1:5)

colnames(df) <- "cat" # This works
colnames( get('df') ) <- "cat" # error
colnames( eval(parse(text='df')) ) <- "cat" # error

The error is

Error in colnames(get("df")) <- "cat" : 
target of assignment expands to non-language object
jbaums
  • 27,115
  • 5
  • 79
  • 119
Heisenberg
  • 8,386
  • 12
  • 53
  • 102
  • [`df`](http://stat.ethz.ch/R-manual/R-patched/library/stats/html/Fdist.html) is a standard function; your code shadows it's definition; `df` is not a good name for a global variable. – sds Mar 11 '14 at 20:44
  • ah the problems of working on a small screen! Thanks for linkong that @Thomas – infominer Mar 11 '14 at 20:49

2 Answers2

1

get retrieve the actual object, but that is not why the code does not work.

Note that

x <- get('df')
colnames(x) <- 'cat'

does work but that

get('df') <- 34

and

sqrt(4) <- 2

do not work.

The reason that they do not work is because of the order in which R evaluates things (see here for the actual C code that produced the error). R is expanding colnames(x) into

get('df') <- `colnames<-`(x, y)

This is not valid, like get('df') <- 34 or sqrt(4), because you cannot assign the result of a function call to value.

Christopher Louden
  • 7,540
  • 2
  • 26
  • 29
-1

Please use assign

assign(names(eval(as.name("df"))), "cat")

The reason parse(text='df') will not work is because it returns an expression that is evaluated by eval and for deails please see the answer @Thomas linked to!

infominer
  • 1,981
  • 13
  • 17