【问题标题】:Renaming data frame columns using symbolic names from stored variables?使用存储变量中的符号名称重命名数据框列?
【发布时间】:2020-03-06 04:52:37
【问题描述】:

我正在构建一个函数,该函数需要我重命名数据框中的列,其中原始列名存储在用户输入的变量中。

#self$options$DV is a string identifying the column of interest, such as 'chosenvarname':    

DVlabel <- self$options$DV

但是,dplyr::rename 函数在使用此变量或其符号链接时不起作用:

df1 <-plyr::rename(df1,c(DVlabel='DV'))

df1 <-plyr::rename(df1,c(self$options$DV='DV'))

即使将 DVlabel 设置为等于数据框中的有效列名,它仍然不起作用

它只有在使用实际列名时才能正常工作,这让我觉得这个函数不适用于符号链接:

df1 <-plyr::rename(df1,c(OriginalColumnName='DV'))

Is there another way to use the column name identified in self$options$DV as the basis for renaming that same column to something else? 

Put differently, is there any way to rename a column using symbolic links to the column name that don't otherwise exist in the data? 

Alternatively, is there some way to construct a column reference, such as data$var1, where the "var1" component is extracted from some other variable (e.g., DVlabel or self$options$DV?)

【问题讨论】:

  • 很抱歉最后几行被格式化为代码。我不知道如何让 $ 字符正确显示。

标签: r


【解决方案1】:

我通过使用以下重命名列找到了解决此问题的方法:

colnames(df1)[colnames(df1) == self$options$DV] <- 'DV'

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 2012-04-28
    • 2018-01-04
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    相关资源
    最近更新 更多