R中的用户定义函数,具有聚合功能

时间:2018-04-08 21:43:56

标签: r data.table

我试图写一个R自定义函数。但我对这一部分比较陌生,所以我一直在努力解决以下问题。

  1. 我想要将Price == Number和Price!= Number的数据进行子集化,但是当我运行该函数时,我得到的表有4列和0变量。

  2. 当我想在列之间进行聚合时,我写的内容也是错误的。

  3. 我的数据

    Name1   Name2   Price   Number
      A       F      6        6
      A       D      5        5
      A       E      2        2
      B       F      4        9
      B       D      7        8
      C       F      4        4
      C       E      2        6
    

    我的功能

    MyFun  <- function(Master_Table, Desired_ColumnA, Desired_ColumnB){
    
      Table1 <- Master_Table[(Desired_ColumnA== Desired_ColumnB)]
      Table2 <- Master_Table[!(Desired_ColumnA== Desired_ColumnB)]
    
      Table2$NewCol  = abs(Table2$Desired_ColumnA - Table2$Desired_ColumnB)
    
      return(Table1)
      return(Table2)
    
    }
    

    测试

    MyTest <- MyFun(Data, Price, Number)
    

    预期输出

    表1:

    Name1   Name2   Price   Number
      A       F      6        6
      A       D      5        5
      A       E      2        2
      C       F      4        4
    

    表2:

        Name1   Name2   Price   Number   New
          B       F      4        9       5
          B       D      7        8       1
          C       E      2        6       4
    

    这将是我整个职能的第一步。如果有人对此有所了解,请告诉我,任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

  1. 函数不能包含多个return语句。如果您想要返回多个对象,我建议您将它们放在list并返回list

  2. 您的子集/过滤不正确。您希望根据涉及两列值的特定条件过滤。请注意我的子集化命令中的逗号。

  3. 您需要将列名称作为字符向量传递。

  4. 这个怎么样?

    f <- function(df, col1, col2) {
    
        # Subset data
        df1 <- df[df[col1] == df[col2], ];
        df2 <- df[df[col1] != df[col2], ];
    
        # Calculate NewCol
        df2["NewCol"] <- abs(df2[col1] - df2[col2]);
    
        # Return data.frames as list
        return(lst(df1, df2));
    }
    f(df, "Price", "Number");
    #$df1
    #  Name1 Name2 Price Number
    #1     A     F     6      6
    #2     A     D     5      5
    #3     A     E     2      2
    #6     C     F     4      4
    #
    #$df2
    #  Name1 Name2 Price Number NewCol
    #4     B     F     4      9      5
    #5     B     D     7      8      1
    #7     C     E     2      6      4
    

    样本数据

    df <- read.table(text =
        "Name1   Name2   Price   Number
      A       F      6        6
      A       D      5        5
      A       E      2        2
      B       F      4        9
      B       D      7        8
      C       F      4        4
      C       E      2        6", header = T)
    
相关问题