我正在尝试编写R自定义函数。但是我对于这部分还比较陌生,因此我一直在努力解决以下问题。
我想在Price == Number和Price!= Number的情况下对数据进行子集化,但是当我运行该函数时,得到的表具有4列和0变量。
当我想在列之间进行聚合时,我写的内容也是错误的。
我的资料
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
这将是我整个工作的第一步。如果有人对此有所了解,请告诉我,我们将不胜感激!
您的代码存在一些问题。
一个函数不能有多个return
语句。如果您想返回多个对象,建议您将它们放在中,list
然后返回list
。
您的子集/过滤不正确。您要根据涉及两列中值的特定条件来过滤行。请注意我的子命令中的逗号。
您需要将列名称作为字符向量传递。
这个怎么样?
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句