2017-02-14 32 views
0

比方說,我爲R data.frame:當我用一個函數做一個屬性到R data.frame時,我該如何添加一個屬性?

> x <- data.frame()

我也有一個SQL查詢我用的sprintf()建設:

> (query <- sprintf("select %s from %s %s", "names", "name_table", "where age > 20")) 
[1] "select names from name_table where age > 20" 

我打算在包住這函數以填充數據。框架xquery的結果,只是幾個灑在上面我想告訴我的未來自己用什麼query生成數據。框架x。我想用電話做這attr()像這樣:

> attr(x, "query") <- query 
> str(x) 
'data.frame': 0 obs. of 0 variables 
- attr(*, "query")= chr "select names from name_table where age > 20" 

因爲函數是要看起來像

answer_maker <- function(col_names, table_name, condtions) { 

        query <- sprintf("select %s from %s %s", col_names, table_name, conditions) 

        data.frame(sql(query)) 

    ############## WHAT DO I DO HERE? 
    ############## I want to type something py-like ...self.attr()? 
        attr(self, "query") <- query 
       } 

後來我將能夠做到以下幾點

> my_first_answer <- answer_maker("names", "name_table", "where age > 20") 
> attr(my_first_answer, "query") 
[1] "select names from name_table where age > 20" 

回答

1

請注意,R中的數據庫函數通常會返回一個數據框,因此您不必填充空的現有數據框。下面我們使用sqldf包來保持示例自包含和可重複的,但是您可以替換您正在使用的任何類型的數據庫訪問。 (通常,您將需要創建一個數據庫連接,並把它傳遞到answer_maker但在這個例子中,由於我們使用sqldf並不需要它。)

library(sqldf) 
name_table <- data.frame(names = letters, age = 1:26) # test data 

answer_maker <- function(col_names, table_name, conditions) { 
     query <- sprintf("select %s from %s %s", col_names, table_name, conditions) 
     ans <- sqldf(query) 
     attr(ans, "query") <- query 
     ans 
} 

ans <- answer_maker("names", "name_table", "where age > 20") 

,並提供:

> ans 
    names 
1  u 
2  v 
3  w 
4  x 
5  y 
6  z 

> attr(ans, "query") 
[1] "select names from name_table where age > 20" 

引用類使用R的參考類,我們可以定義一個包含數據和查詢字段的類,並存儲查詢並運行它,以便每個輸出對象使用.self

Query <- setRefClass("Query", fields = c("data", "query"), 
    methods = list(
     setQuery = function(col_names, table_name, conditions) { 
      query <<- sprintf("select %s from %s %s", col_names, table_name, conditions) 
      .self 
     }, 
     runQuery = function() { 
      data <<- sqldf(query) 
      .self 
     })) 

qq <- Query$ 
     new()$ 
     setQuery("names", "name_table", "where age > 20")$ 
     runQuery() 

捐贈:

> qq$data 
    names 
1  u 
2  v 
3  w 
4  x 
5  y 
6  z 
> qq$query 
[1] "select names from name_table where age > 20" 
+0

這是偉大的,謝謝。但是你的迴應是否暗示在像這樣的構造器對象中沒有'self.thing'風格的賦值? – d8aninja

+1

如果您正在尋找OO風格,那麼有許多對象系統(S3,S4,Reference Classes)以及定義其他OO系統(proto,oo.R,R6)的多個包。我們在答案結尾的參考類的附加部分中說明了參考類。 –

+0

哇...真棒 - 非常感謝你的時間! – d8aninja

相關問題