【问题标题】:Rename columns of dataframe and access them with that name重命名数据框的列并使用该名称访问它们
【发布时间】:2014-12-10 11:14:33
【问题描述】:

我有一个循环向数据框添加几列

我知道如何用 colnames 重命名列,但我不能使用这些新名称来访问这些列 例如。我在我的框架中添加了一个编号为 22 的列。

units = 10
my.frame[units+1] = 22

我可以将此列重命名为:

colnames(my.frame)[units+1] = "twentytwo_column"

但如果我想在代码后面的某个地方访问此列,我必须这样做:

my.frame[units+1]

如果我可以像这样访问它会增加可理解性:

my.frame[twentytwo_column]

有没有办法做到这一点?

【问题讨论】:

  • 当然:my.frame["twentytwo_column"]my.frame$twentytwo_column

标签: r dataframe rename


【解决方案1】:

您应该阅读基本的对象提取(参见? Extract)。

您需要在括号中添加逗号(和引号)以从 data.frame 中提取列:my.frame[, units+1]my.frame[, "twentytwo_column"]

此外,通常在 data.frames 上使用 names 而不是 colnames

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2019-06-24
    • 1970-01-01
    • 2019-01-10
    • 2019-09-26
    • 2019-08-19
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多