2012-01-18 37 views
4

我使用的data.table相当多。它工作的很好,但我发现它花了很长时间来转换我的语法,以便利用二进制搜索。在使用data.table的R中,如何排除行,如何在整数列中包含NA值

在下面的数据表会怎么选择1所有行,包括在CPT值是NA但不包括行,其中的CPT值是23456或10000

cpt <- c(23456,23456,10000,44555,44555,NA) 
description <- c("tonsillectomy","tonsillectomy in >12 year old","brain transplant","castration","orchidectomy","miscellaneous procedure") 
cpt.desc <- data.table(cpt,description) 

setkey(cpt.desc,cpt) 

下面这行工作,但我认为,它使用矢量扫描方法而不是二进制搜索(或二进制排除)。有没有办法通过二进制方法删除行?

cpt.desc[!cpt %in% c(23456,10000),] 

回答

2

只有部分答案,因为我是新来的data.table。自连接适用于数字,但字符串也一样。我确信其中一个专业数据表会知道该怎么做。

library(data.table) 

n <- 1000000 
cpt.desc <- data.table(
    cpt=rep(c(23456,23456,10000,44555,44555,NA),n), 
    description=rep(c("tonsillectomy","tonsillectomy in >12 year old","brain transplant","castration","orchidectomy","miscellaneous procedure"),n)) 

# Added on revision. Not very elegant, though. Faster by factor of 3 
# but probably better scaling 
setkey(cpt.desc,cpt) 
system.time(a<-cpt.desc[-cpt.desc[J(23456,45555),which=TRUE]]) 
system.time(b<-cpt.desc[!(cpt %in% c(23456,45555))]) 
str(a) 
str(b) 

identical(as.data.frame(a),as.data.frame(b)) 

# A self-join works Ok with numbers 
setkey(cpt.desc,cpt) 
system.time(a<-cpt.desc[cpt %in% c(23456,45555),]) 
system.time(b<-cpt.desc[J(23456,45555)]) 
str(a) 
str(b) 

identical(as.data.frame(a),as.data.frame(b)[,-3]) 

# But the same failes with characters 
setkey(cpt.desc,description) 
system.time(a<-cpt.desc[description %in% c("castration","orchidectomy"),]) 
system.time(b<-cpt.desc[J("castration","orchidectomy"),]) 
identical(as.data.frame(a),as.data.frame(b)[,-3]) 

str(a) 
str(b) 
+0

您的代码为某些值选择。不过,我正在尝试针对(或排除或删除)具有特定值的行进行选择。 – Farrel 2012-01-19 13:59:06

+0

尝试编辑后的版本。 – 2012-01-20 10:49:33

+0

您的代码仍然存在问题。当你设置数据表时,你使用了44555作为一个值,但是我在后面的行中犯了一个印刷错误,因为你使用了45555.此外,当你想在J命令中使用OR函数时,你不能使用J值,第二个值),因为这将查找第一个键中的第一个值和第二个键中的第二个值。相反,您必须使用'J(c(第一个值,第二个值))'。检查一下,看看你是否同意。之后,我会再看。我对你的技术很感兴趣。 – Farrel 2012-01-20 16:46:14

相关问题