2015-11-22 20 views
5

從我的簡單data.table,例如,像這樣:「object」ansvals'not found「錯誤 - 這是什麼意思?

dt1 <- fread(" 
col1 col2 col3 
AAA ab cd 
BBB ef gh 
BBB ij kl 
CCC mn nm") 

我想提出新的表格,例如,像這樣:

dt1[, 
    .(col3, new=.N), 
    by=col1] 

> col1 col3 new 
>1: AAA cd 1 
>2: BBB gh 2 
>3: BBB kl 2 
>4: CCC op 1 

這工作得很好,當我指出的列名明確。但是,當我讓他們在變量,並嘗試使用with=F,這給出了一個錯誤:

colBy <- 'col1' 
colShow <- 'col3' 

dt1[, 
    .(colShow, 'new'=.N), 
    by=colBy, 
    with=F] 
# Error in `[.data.table`(dt1, , .(colShow, new = .N), by = colBy, with = F) : object 'ansvals' not found 

我找不到任何關於此錯誤的任何信息爲止。

回答

7

爲什麼您收到此錯誤信息的原因是,使用with=FALSE當你告訴data.table治療j,好像它是一個數據幀。因此,它需要一個列名向量,而不是表達式j中的​​。

?data.table文檔約with

By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. When with=FALSE j is a character vector of column names or a numeric vector of column positions to select, and the value returned is always a data.table.

當您使用with=FALSE,你必須在j()這樣之前選擇COLUMNNAMES沒有.dt1[, (colShow), with=FALSE]。其他選項是dt1[, c(colShow), with=FALSE]dt1[, colShow, with=FALSE]。相同的結果可通過使用dt1[, .(col3)]

綜上所述獲得:with = FALSE用於選擇列data.frame方式。所以,你應該這樣做。

而且通過使用by = colBy你告訴data.table評估j這與with = FALSE矛盾。

?data.tablej文檔:

A single column name, single expresson of column names, list() of expressions of column names, an expression or function call that evaluates to list (including data.frame and data.table which are lists, too), or (when with=FALSE) a vector of names or positions to select.

j is evaluated within the frame of the data.table; i.e., it sees column names as if they are variables. Use j=list(...) to return multiple columns and/or expressions of columns. A single column or single expression returns that type, usually a vector. See the examples.

參見點data.table1.d and 1.g of the introduction vignette


ansvalsdata.table內部使用的名稱。你可以看到它出現在代碼中使用CTRL +˚F(Windows)或CMD + ˚F(MACOS)here

+0

謝謝你的解釋!當列名存儲在變量中時,它是否意味着只有'by ='才能使用? –

+0

@VasilyA這當然是可能的,但你必須以正確的方式做到這一點。見[這裏](http://stackoverflow.com/questions/32940580/convert-some-column-classes-in-data-table/32942319#32942319)或[這裏](http://stackoverflow.com/questions/ 33772830/how-to-set-multiple-columns-and-selected-rows-in-data-table-to-value-from-other/33774525#33774525)舉例。您可能還想閱讀[入門指南](https://github.com/Rdatatable/data.table/wiki/Getting-started) – Jaap

+0

,在這些例子中,by ='完全不用,這個使它變得非常不同......我將再次閱讀入門指南,並可能發佈一個單獨的問題,指明我確實需要什麼。 –

1

錯誤object 'ansvals' not found看起來像一個bug給我。它應該是一個有用的信息或者只是工作。我已經提交issue #1440鏈接回到這個問題,謝謝。

Jaap是完全正確的。從他的回答中,您可以使用get()這樣的j

dt1 
# col1 col2 col3 
#1: AAA ab cd 
#2: BBB ef gh 
#3: BBB ij kl 
#4: CCC mn nm 
colBy 
#[1] "col1" 
colShow 
#[1] "col3" 
dt1[,.(get(colShow),.N),by=colBy] 
# col1 V1 N 
#1: AAA cd 1 
#2: BBB gh 2 
#3: BBB kl 2 
#4: CCC nm 1 
+1

謝謝你馬特!我只是想提出一個問題,詢問get()是否可以成爲一個好的解決方案:) –