如何在R6中正确编写类方法并链接它们
我需要创建自己的类对象,该对象采用数据框并具有方法“ get_data”来选择数据框架, “选择”以通过其名称选择列和“滤镜”以用某些值过滤行。 选择和过滤器与Dplyr相似,但不使用DPLYR。
我希望他们可以这样链接:
result <- df_object$get_data(df)$select(col1, col2, period)$filter(period)
我该怎么做,以使“过滤器”方法可以过滤已经选择的值?现在它过滤初始数据集。另外,如何更改方法,以使选择和过滤不需要数据参数?请给我一些提示,我觉得我这样做的方法是错误的。 Do I need to add some fields to class?
dataFrame <- R6Class("dataFrame",
list(data = "data.frame"),
public = list(
get_data = function(data) {data},
select_func = function(data, columns) {data[columns]},
filter_func = function(data, var) {data[var, ]}
))
# Create new object
df_object <- dataFrame$new()
# Call methods
df_object$get_data(df)
df_object$select_func(df, c("month", "forecast"))
df_object$filter_func(df[df$month %in% c(1, 2), ])
I need to create my own class object that takes a dataframe and has methods 'get_data' to choose dataframe,
'select' to select columns by their names and 'filter' to filter rows with certain values.
Select and filter are a kind of similar to dplyr, but without using dplyr.
I would like they could be chained like this:
result <- df_object$get_data(df)$select(col1, col2, period)$filter(period)
What can I do so that 'filter' method would filter already selected values? Now it filters initial dataset. Also how to change methods so that select and filter wouldn't need data argument? Please give me some tips, I feel like I'm doing it a wrong way. Do I need to add some fields to class?
dataFrame <- R6Class("dataFrame",
list(data = "data.frame"),
public = list(
get_data = function(data) {data},
select_func = function(data, columns) {data[columns]},
filter_func = function(data, var) {data[var, ]}
))
# Create new object
df_object <- dataFrame$new()
# Call methods
df_object$get_data(df)
df_object$select_func(df, c("month", "forecast"))
df_object$filter_func(df[df$month %in% c(1, 2), ])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要链成员函数,则需要这些成员功能才能返回
self
。这意味着R6对象必须修改其包含的数据。由于R6的好处是减少副本,因此我可能会保留数据的完整副本,并具有select_func
和filter_func
更新一些行和列索引:这允许我们要链过滤器并选择方法:
并且我们的选择方法也可以采用名称:
为了完整性,您需要某种类型的安全性,我还将添加一个重置方法来删除所有过滤。这有效地为您提供了一个数据框架,其中过滤和选择是无损的,这实际上可能非常有用。
由
If you want to chain member functions, you need those member functions to return
self
. This means that the R6 object has to modify the data it contains. Since the benefit of R6 is to reduce copies, I would probably keep a full copy of the data, and haveselect_func
andfilter_func
update some row and column indices:This allows us to chain the filter and select methods:
and our select method can take names too:
For completeness, you need some type safety, and I would also add a reset method to remove all filtering. This effectively gives you a data frame where the filtering and selecting are non-destructive, which could actually be very useful.
Created on 2022-05-01 by the reprex package (v2.0.1)