命名动态选择的data.frame列

时间:2016-06-13 20:00:45

标签: r dataframe eval columnname

我试图命名数据框的列,但动态选择数据框。知道为什么这不起作用吗?下面是一个例子,但在我的实际情况中,我得到了一个不同的错误。截至目前,我只想知道导致错误的原因:

  

文件错误(文件名," r"):无法打开连接
  另外:警告信息:
  在文件中(文件名," r"):
    无法打开文件' df':没有这样的文件或目录

#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

1 个答案:

答案 0 :(得分:14)

它不起作用,因为R不希望你使用assign和(argh!)eval(parse())这些基本的东西。列表!这就是上帝创造名单的原因!

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
相关问题