【问题标题】:R - Pass a string to a formula for dataframe subset [duplicate]R - 将字符串传递给数据帧子集的公式[重复]
【发布时间】:2014-11-10 19:38:34
【问题描述】:

我有一个名为 returns 的数据框,其中包含不同的列,例如 simple。我通常通过returns$simple 访问它。现在我需要将这些列传递给一个函数。我尝试了很多我在板上找到的东西(as.formulaparsepaste 等),但都没有奏效。

test = function(x) 
{ 
  returns$x
}
test(simple)

【问题讨论】:

    标签: r string function


    【解决方案1】:

    您可以使用括号表示法访问您的列。以下是你的做法:

    test = function(x) 
    { 
        returns[,x]
    }
    test("simple")
    

    或者简单地说(不使用函数):

    returns[, column_name]
    

    【讨论】:

      【解决方案2】:

      您可以根据列的名称使用[[ 来处理列中的值。如果不想在调用函数时引用列名,则必须使用deparsesubstitute

      test <- function(x) 
      { 
        xc <- deparse(substitute(x))
        returns[[xc]]
      }
      
      test(simple)
      

      【讨论】:

        【解决方案3】:

        试试这个

        returns[,x]                    # a
        

        或获取列 id,使用哪个。

        which(names(returns)==x)       # b
        

        另一个想法是使用grep

        grep("^x$", colnames(returns)) # c
        grep("^x$", names(returns))    # d
        

        【讨论】:

        • @Davik,感谢您的指正:)
        猜你喜欢
        • 2021-12-01
        • 2021-09-16
        • 1970-01-01
        • 2023-02-24
        • 2013-01-18
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多