簡體   English   中英

data.table - 基於名稱為列的變量的子集

[英]data.table - subsetting based on variable whose name is a column, too

這可能data.table在我使用其參數進行過濾的函數中使用data.table時,我經常遇到這種情況。

想象一下,您有一個變量,其值要與data.table的列進行比較並進行過濾。 如果變量的名稱與列的名稱相同怎么辦?

我試過的例子和事情:

DT <- data.table(mtcars)
cyl <- 4
# intended: filter rows where column "cyl" equals the value of variable cyl

# this does not work
DT[cyl == (cyl)]
# this does not work either
DT[cyl == `cyl`]

Data.table在數據表本身的環境中運行,因此您可能需要指定從中獲取值的位置

DT[cyl == get("cyl", envir = parent.frame())]

只需指定范圍界定:

DT[cyl == globalenv()$cyl]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM