我的感觉是你可以通过使用来做到这一点R6 https://cran.r-project.org/web/packages/R6/vignettes/Introduction.html和主动绑定。
- R6 方法属于对象,而不是泛型。
- R6 对象是可变的:通常的修改时复制语义不适用。
考虑到这一点,我们可以创建一个示例。在这里,我们创建了 iris 数据集的两个视图,在其中使用两个不同的列名称访问同一列。通过任一列名称进行的更改都将更新共享的私有虹膜数据集。
我是 R6 的粉丝,因为它提供了一种维护(在本例中)数据帧引用语义的方法,同时允许多种方式引用数据集。
注意。我希望这能为您指明正确的方向。
R6 示例(这里我们创建 iris 数据集的两个视图):
require(R6)
data(iris)
dataframe_factory <- R6Class(
"dataframe_factory",
portable = FALSE,
lock_objects = FALSE,
private = list(
..iris_data = iris
),
active = list(
# add the binding here
Sepal.Length = function(x, ...) {
if ( missing(x) ) {
private$..iris_data$Sepal.Length
} else {
private$..iris_data$Sepal.Length[...] <<- x
}
},
another.Sepal.Length = function(x, ...) {
if ( missing(x) ) {
private$..iris_data$Sepal.Length
} else {
private$..iris_data$Sepal.Length[...] <<- x
}
}
)
)
# Create the DataFrame
my_Dataframe <- dataframe_factory$new()
# Retrieve the alias
my_Dataframe$Sepal.Length
my_Dataframe$another.Sepal.Length
my_Dataframe$Sepal.Length[1] <- 5
my_Dataframe$Sepal.Length[1]
my_Dataframe$another.Sepal.Length[2] <- 8
my_Dataframe$another.Sepal.Length[2]
my_Dataframe$Sepal.Length
my_Dataframe$another.Sepal.Length
head(my_Dataframe$Sepal.Length,2)
my_Dataframe$Sepal.Length[1:2]
identical(my_Dataframe$Sepal.Length, my_Dataframe$another.Sepal.Length)
identical(my_Dataframe$Sepal.Length[1], my_Dataframe$another.Sepal.Length[1])
identical(my_Dataframe$Sepal.Length[1:2], my_Dataframe$another.Sepal.Length[1:2])
R6 控制台控制台输出:
> require(R6)
> data(iris)
> dataframe_factory <- R6Class(
+ "dataframe_factory",
+ portable = FALSE,
+ lock_objects = FALSE,
+ private = list(
+ ..iris_data = iris
.... [TRUNCATED]
> # Create the DataFrame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7 6.9 5.8 6.8 6.7 6.7 6.3 6.5 6.2 5.9
> my_Dataframe$another.Sepal.Length
[1] 5.0 8.0 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1
[21] 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1
[41] 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2
[61] 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7
[81] 5.5 5.5 5.8 6.0 5.4 6.0 6.7 6.3 5.6 5.5 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7
[101] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7 6.0
[121] 6.9 5.6 7.7 6.3 6.7 7.2 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7 6.3 6.4 6.0 6.9
[141] 6.7 6.9 5.8 6.8 6.7 6.7 6.3 6.5 6.2 5.9
> head(my_Dataframe$Sepal.Length,2)
[1] 5 8
> my_Dataframe$Sepal.Length[1:2]
[1] 5 8
> identical(my_Dataframe$Sepal.Length, my_Dataframe$another.Sepal.Length)
[1] TRUE
> identical(my_Dataframe$Sepal.Length[1], my_Dataframe$another.Sepal.Length[1])
[1] TRUE
> identical(my_Dataframe$Sepal.Length[1:2], my_Dataframe$another.Sepal.Length[1:2])
[1] TRUE