![](/img/trans.png)
[英]Update a subset of values in data.table column with values from another data.table column
[英]How to subset data.table on the basis of a values in a certain column number
在data.table中,一種基於列號的數值向量對表進行子集化的方法是使用with=FALSE
。
我正在嘗試根據列號的數值向量遍歷data.table,以尋找符合特定條件的行 ,如下所示:
require(data.table)
ab=data.table(id=c("geneA", "geneB", "geneC", "geneA", "geneA", "geneB", "", "NA"),
co1=c(1,2,3,0,7), co2=c(0,0,4,5,6), nontarget=c(9,0,7,6,5),
co3=c(0,1,2,3,4))
target_col_nums=grep('co', colnames(ab))
##Data.table doesn't treat colnames(ab)[i] as one of the
## column name variables, and with=F only seems to work for j in dt[i,j,by]
for (i in target_col_nums){
print(ab[colnames(ab)[i]>3])
}
##This produces the desired output
ab[co1>3]
ab[co2>3]
ab[co3>3]
在我的情況下,我的實際表很大,因此我不能使用colnames本身。
我希望這是對社區有用的問題。
for (col in grep('co', names(ab), value = T))
print(ab[get(col) > 3])
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
# id co1 co2 nontarget co3
#1: geneC 3 4 7 2
#2: geneA 0 5 6 3
#3: geneA 7 6 5 4
#4: NA 3 4 7 2
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
您可以將( eval
)列作為表達式求值
for (i in target_col_nums){
expr <- paste0(colnames(ab)[i], ">3")
print(ab[eval(parse(text = expr)), ])
}
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
# id co1 co2 nontarget co3
#1: geneC 3 4 7 2
#2: geneA 0 5 6 3
#3: geneA 7 6 5 4
#4: NA 3 4 7 2
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
或者您可以嘗試在問題中將變量作為data.table列名的任何建議
您可以對方法進行很小的調整,但仍然可以使用列號來解決(盡管在這種情況下,由於您以編程方式獲得了列數,所以危害不大),但通常是不好的做法:
target_cols = names(ab)[grepl("co", names(ab))]
sapply(target_cols, function(jj) print(ab[get(jj) > 3]))
如果NULL
輸入會使人分心,則將其invisible
,否則會打擾您。
我們可以在.SDcols
指定'i'並使用.SD
上的條件來獲取邏輯向量,該邏輯向量可用於子集行。
for(i in target_col_nums){
print(ab[ab[, .SD[[1L]] >3, .SDcols = i]])
}
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
# id co1 co2 nontarget co3
#1: geneC 3 4 7 2
#2: geneA 0 5 6 3
#3: geneA 7 6 5 4
#4: NA 3 4 7 2
# id co1 co2 nontarget co3
#1: geneA 7 6 5 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.