【问题标题】:R: Implication of tibble inheritanceR: tibble 继承的含义
【发布时间】:2019-04-09 08:40:24
【问题描述】:

我试图理解继承 tibble 类的行为并面临以下情况。我创建了一个类myClass,我为它定义了一个打印函数:

library(dplyr)
library(tibble)

myClass<-function(x,y,var){
new_tibble(data.frame(x=x,y=y),oneVar=var,subclass='myClass')}

myObj=myClass(rnorm(10),rnorm(10),'s')
myObj2=myClass(rnorm(10),rnorm(10),'s2')


print.myClass<-function(x,...){
 print(as_tibble(x))
   print(slot(x,'oneVar'))
 }    

然后,让我们尝试使用一些 dplyr 函数来修改我的对象:

myObj %>% arrange(x) %>% filter(x>0)
# A tibble: 6 x 2
      x       y
  <dbl>   <dbl>
1 0.183  0.826 
2 0.801  0.504 
3 1.19   2.53  
4 1.24   0.238 
5 1.28  -0.0557
6 1.69  -0.734 
[1] "s"

看起来调用 filterarrange 只是修改了我的对象的 tibble 部分,而其他插槽保持不变,这可能是一个有用的属性可以利用。

然后让一些不太明显的东西,让“row_bind”成为两个 myClass 对象:

bind_rows(myObj,myObj2)
# A tibble: 20 x 2
         x       y
     <dbl>   <dbl>
 1  0.801   0.504 
 2  1.19    2.53  
 3 -1.69    0.549 
 4  1.24    0.238 
 5 -0.109  -1.05  
 6 -0.117   1.29  
 7  0.183   0.826 
 8  1.28   -0.0557
 9 -1.73   -0.784 
10  1.69   -0.734 
11 -0.216  -1.31  
12 -0.335  -0.600 
13 -1.09   -0.129 
14 -0.0854  0.887 
15  1.07   -0.151 
16 -0.145   0.330 
17 -1.17   -3.23  
18 -0.819  -0.772 
19  0.685   0.287 
20 -0.320  -1.22  
Error in slot(x, "oneVar") : 
  no slot of name "oneVar" for this object of class "myClass"

这里缺少“oneVar”插槽,因此“myClass”对象的完整性被破坏。我理解,这种行为不一定是问题,但请尝试了解它的来源。

然后是我的问题:

bind_rows 中涉及的哪些机制(例如filter 中未涉及)导致插槽丢失? 它是如何工作的?

【问题讨论】:

    标签: r oop dplyr tibble


    【解决方案1】:

    我觉得bind_rows 不是为保留用户定义的插槽而设计的。另一方面,基础 R rbind 保留插槽并使用第一个对象中的插槽,如下所示。我也试过data.table::rbindlist(list(myObj, myObj2)),但输出不再是myClass。这就是这些功能是如何根据不同的要求和行为创建的。

    rbind(myObj, myObj2)
    # # A tibble: 20 x 2
    #   x       y
    #   <dbl>   <dbl>
    # 1 -0.0978   0.629 
    # 2  0.406   -0.889 
    # 3  0.766   -0.746 
    # 4 -0.715    0.872 
    # 5  0.617    1.05  
    # 6  0.353   -1.49  
    # 7 -0.595   -1.41  
    # 8 -3.20    -0.262 
    # 9 -1.33     0.232 
    # 10  0.835   -0.751 
    # 11 -0.00793  0.807 
    # 12  0.177    0.680 
    # 13 -1.10     0.857 
    # 14 -0.679    1.79  
    # 15 -1.38     0.0481
    # 16 -1.42     1.02  
    # 17 -1.97     0.732 
    # 18  1.72     1.06  
    # 19 -0.773   -0.594 
    # 20  0.490    0.186 
    # [1] "s"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 2020-10-21
      • 2018-05-08
      • 2019-12-19
      • 1970-01-01
      相关资源
      最近更新 更多