R:在自定义函数中将列名作为变量传递

标签 r function variables dataframe

总的来说,我对 R 和编程很陌生,并且已经在以下几个小时内苦苦挣扎。

我正在尝试创建一个函数,它将一个 df 和一个列名作为变量,根据提供的列名过滤表并打印输出。

example_function <- function(df=df, col=col){
         a <- df[col == 100,]
         b <- filter(df, col == 100)
         print(a)
         print(b)
}

使用 example_function(df=example_df, col='percentage')不起作用,两个变量都只返回列名而不返回数据行(尽管存在值 == 100)。

使用 example_function(df=df, col=percentage) ,所以百分比在这里没有被引号包围,我得到:

Error in [.data.frame(df, col == 100, ) : object 'percentage' not found



但是,当我运行 example_function(df=example_df, col=example_df$percentage) 时我得到了正确的结果,我的数据帧按预期返回,只有 example_df$percentage 的那些行等于 100。

我真的希望能够将 df 作为一个变量传递,将列作为另一个变量传递,而无需键入 example_df$percentage每次我都希望能够对许多不同的数据帧重复使用该函数,并且输入似乎是多余的。

基于此,我然后修改了函数,认为我可以只使用 df$col在函数中,它将评估为 example_df$percentage并像上面那样工作:
example_function <- function(df=df, col=col){
     a <- df[df$col == 100,]
     b <- filter(df, df$col == 100)
     print(a)
     print(b)
}

但是现在我在使用 example_function(df=example_df, col=percentage) 时遇到另一个错误或路过时col='percentage' :

Error in filter_impl(.data, quo) : Result must have length 19, not 0



是否有任何机构能够帮助我解决这个问题,或者为我指明正确的方向以了解为什么我正在做的事情不起作用?

非常感谢

这是我正在使用的数据框的一个示例(虽然我的真实数据框会有更多列,但我希望它不会对这个示例产生影响。)
 name    | percentage
    -----------------------
    tom      |  80
    john     |  100
    harry    |  99
    elizabeth|  100
    james    |  50




  example_df <- structure(list(name = structure(c(5L, 4L, 2L, 1L, 3L), .Label = c("elizabeth", 
    "harry", "james", "john", "tom"), class = "factor"), percentage = c(80L, 
    100L, 99L, 100L, 50L)), .Names = c("name", "percentage"), class = "data.frame", row.names = c(NA, 
    -5L))
  • 作为说明,我已将本示例中的 col=names 更新为 col=percentage,以更准确地表示我在做什么。在我试图概括这个例子时,我使用了 col=names 并且现在意识到这不是一个很好的例子(因为你非常正确地断言“名称”永远不可能是数字)。然而,上述问题对我来说仍然存在。

  • ** 更新:我设法让它与以下一起工作:
    example_function <- function(df=df, col=col){
         a <- df[df[col] == 100,]
         print(a)
    }
    

    路过example_function(df=example_df, col='percentage')

    最佳答案

    第一排example_function应该

    a <- df[df[[col]] == 100,]
    

    当你分解它时,df[['names']] == 100将为您提供与 df 的哪些行相对应的逻辑列表有一个 names值为 100。但是 'names' == 100是荒谬的:它总是错误的。

    关于R:在自定义函数中将列名作为变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47005768/

    相关文章:

    c - 如何在c中定义常用函数

    c - 如何在 Cobol 中打印变量名称

    javascript - shiny点击DT后弹窗

    r - 意外的 dplyr::bind_rows() 行为

    r - 无法编译 r markdown 代码

    javascript - 在 mouseenter 上使用 javascript 连续循环 div 上的颜色

    azure - 将函数部署到 Azure 后出现错误 : 'Could not load file or assembly ' System. ServiceModel,版本=4.0.0.0'

    Bash 删除路径中的前导/

    xslt - 使用 XSLT 变量作为字段名称

    r - 使用R和XML包进行Web爬取