Search code examples
rdataframeevalr-colnames

name columns of dynamically chosen data.frame


I am trying to name the columns of a data frame, but the data frame is chosen dynamically. Any idea why this does not work? Below is an example, but in my real case, I get a different error. As of now, I would just like to know what causes either of the errors:

Error in file(filename, "r") : cannot open the connection
In addition: Warning message:
In file(filename, "r") :
cannot open file 'df': No such file or directory

#ASSIGN data frame name dynamically
> assign(as.character("df"), data.frame(c(1:10), c(11:20)))
> 
#IT WOrked
> df
   c.1.10. c.11.20.
1        1       11
2        2       12
3        3       13
4        4       14
5        5       15
6        6       16
7        7       17
8        8       18
9        9       19
10      10       20
> 
#Call the data frame dynamically, it works
> eval(parse(text = c("df")))
   c.1.10. c.11.20.
1        1       11
2        2       12
3        3       13
4        4       14
5        5       15
6        6       16
7        7       17
8        8       18
9        9       19
10      10       20
> 
#name the columns
> colnames(df) <- c("a", "b")
> df
    a  b
1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20
> 
#name columns of dynamically chosen data frame, returns and error
> colnames(eval(parse(text = c("df")))) <- c("c", "d")
  Error in colnames(eval(parse(text = c("df")))) <- c("c", "d") : 
   target of assignment expands to non-language object

Solution

  • It doesn't work because R doesn't want you to use assign and (argh!) eval(parse()) for this sort of basic stuff. Lists! This is why the Lord created lists!

    l <- list()
    l[["df"]] <- data.frame(c(1:10), c(11:20))
    colnames(l[["df"]]) <- c("a","b")
    > l
    $df
        a  b
    1   1 11
    2   2 12
    3   3 13
    4   4 14
    5   5 15
    6   6 16
    7   7 17
    8   8 18
    9   9 19
    10 10 20