【问题标题】:Return a variable name after applying a function on a vector in R在R中的向量上应用函数后返回变量名
【发布时间】:2017-09-15 08:55:23
【问题描述】:

例如,假设我的项目有许多对象,我已将它们放入向量中。

foo <- 10
bar <- 9
pleb <- 4
eian <- 8

pizzaParlor <- c(foo, bar, pleb, eian)

通过创建下面的函数,我可以快速确定这家披萨店最好吃的东西。

tastiestFood = function(anyVector) {
    paste("Item #", 
          which.max(anyVector), 
          "of", 
          deparse(substitute(anyVector)), 
          "is the tastiest!")
}

tastiestFood(pizzaParlor)
[1] "Item # 1 of pizzaParlor is the tastiest!"

我将如何获得此输出?

[1] "foo"

我遇到的挑战是确保函数的编写方式适用于任何数字向量、任何长度以及不同命名的对象。定义名称向量并提前标记向量会违反这一点(我认为?)。

提前感谢您的帮助。

【问题讨论】:

  • 好吧,如果不以任何形式定义名称,您将无法获得命名输出。您需要有任何与which.max(anyVector) 的位置相对应的字符串才能将该字符串输出到您的paste() 调用中。
  • pizzaParlor &lt;- c(foo=foo, bar=bar, pleb=pleb, eian=eian) ... 然后(如 LeoP. 评论)在您的函数中 names(anyVector)[which.max(anyVector)]
  • 感谢您的评论 Leo + jogo。我的 Python 同事可以直接使用字典调用变量名称,所以我希望 R 中有类似的东西。根据您的说法,向量需要设置为从一开始就指定的名称。如果我有大量未命名的向量来处理嵌套在其中的对象,那么如果我可以直接从变量名中调用该名称,那就太棒了。
  • 从头开始。我查看了 Python 方法,这与我在使用 R 时遇到的问题基本相同。在构建字典时需要预先定义它才能调用变量名。
  • 是的,我看不到您可以从任何对象中获取变量名而不预先定义它们的情况。我下面的解决方案至少会在有名称时使用名称,并且仅在未命名时使用对象内的位置。

标签: r variables object vector names


【解决方案1】:

您可以在函数中检查输入向量中是否存在名称,如果有,则输出它们,否则输出位置。

试试

ifelse(!is.null(names(anyVector)), names(anyVector)[which.max(anyVector)], 
  which.max(anyVector))

在您的paste() 调用中,而不是当前的which.max(anyVector)

数据:

foo <- 10
bar <- 9
pleb <- 4
eian <- 8

pizzaParlor <- c(foo, bar, pleb, eian)
pizzaParlor2 <- c(foo=foo, bar=bar, pleb=pleb, eian=eian)

功能:

tastiestFood = function(anyVector) {
    paste("Item #", 
          ifelse(!is.null(names(anyVector)), names(anyVector)[which.max(anyVector)], 
                 which.max(anyVector)), 
          "of", 
          deparse(substitute(anyVector)), 
          "is the tastiest!")
}

输出:

> tastiestFood(pizzaParlor)
[1] "Item # 1 of pizzaParlor is the tastiest!"

> tastiestFood(pizzaParlor2)
[1] "Item # foo of pizzaParlor2 is the tastiest!"

【讨论】:

    【解决方案2】:

    试试这个:

    foo <- 10
    bar <- 9
    pleb <- 14
    eian <- 8
    
    pizzaParlor <- data.frame(foo, bar, pleb, eian)
    
    tastiestFood = function(anyVector) {
        paste(colnames(anyVector)[which.max(anyVector)])
    }
    
    tastiestFood(pizzaParlor)
    

    输出:

    "pleb"
    

    【讨论】:

    • 我认为这将是一个 Marco,但有一个问题。这假设我正在使用的数据从一开始就设置为 df。如果我被困在我的所有数据都是带有嵌套变量的未标记向量形式的情况下,有没有办法返回变量名?我尝试使用您的逻辑将向量转换为函数内的 df,但未成功...
    • 您能否针对这种情况指定您的代码以获得更多说明?
    猜你喜欢
    • 1970-01-01
    • 2018-05-10
    • 2018-03-03
    • 2017-01-18
    • 2011-04-04
    • 2016-11-29
    • 2020-08-05
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多