2015-04-02 44 views
0

我有两个数据帧“a”和“b”。检查另一个数据帧的给定ID是否存在某个值

str(a) 
'data.frame': 1597 obs. of 2 variables: 
$ id : int ... 
$ age: num ... 

> str(b) 
'data.frame': 12877 obs. of 2 variables: 
$ id  : int ... 
$ code : chr ... 

虽然“id”在“a”中是唯一的,但它不在“b”中。更准确地说,“a”和“b”之间有1:n的关系。我想检查“$ id”中是否有“b”中的某个代码。我怎样才能做到这一点?

我想,我需要这样的:

a$code.I25 <- ifelse(<if there is a$id in b$id and for b$id an entry with "I25" for b$code>, 1, 0) 

遗憾的是有点复杂。 “b $ code”的值不仅仅是“I25”,而是“I25.11”或“I25.12”。但是,我只想比较“I25”,并希望对“I25.11”和“I25.12”两者都适用。这可能吗?

+0

没有B $代码只有这个模式?即I 25.11,I 25.12?您可以使用regexp在data.frame b中创建一个新变量。 – infominer 2015-04-02 19:30:34

回答

0
#create a dummy data.frame for a 
foo.a <- data.frame(id = 1:20,age = rnorm(20,25)) 
foo.b <-data.frame(id = 1:40, 
code = as.character(paste(c("I25","I27"),1:20,sep = "."))) 
#replicate it randomly 
set.seed(357) 
foo.b <-foo.b[sample(nrow(foo.b),75, replace = T),] 
#check for matches 
id.match <-which(foo.b$id %in% foo.a$id) 
#get matching rows 
foo.b[grep("I25",foo.b$code[id.match]),] 
+0

感谢大家; infominer的最后回答迄今为止工作得很好。只剩下一个问题。例如,“I25”中有多个子代码,如“I25.1”,“I25.2”等。但我只想知道这些子代码中是否至少有一个给定的id,在这种情况下,我需要在“foo.a $ i25”中的值“1”,否则为“0”。最简单的方法和最短的(代码行)是什么? – Gurkenhals 2015-04-03 05:49:55

+0

那么接受我的答案呢?至于你的问题,像你在你的文章中那样使用'ifelse'。我将把实施作为一项练习! – infominer 2015-04-03 14:58:48

0

下面是一个例子

id_a = c(1, 2, 3, 23, 19, 11:13, 4, 6) 
id_b = c(1, 2, 2, 5, 8, 11:13, 3, 3) 
code_b = c(rep("I25", 4), rep("I26", 5), "I25") 

a = data.frame(id = id_a, stringsAsFactors = FALSE) 

a 
# id 
# 1 1 
# 2 2 
# 3 3 
# 4 23 
# 5 19 
# 6 11 
# 7 12 
# 8 13 
# 9 4 
# 10 6 

b = data.frame(id = id_b, code = code_b, stringsAsFactors = FALSE) 

b 
# id code 
# 1 1 I25 
# 2 2 I25 
# 3 2 I25 
# 4 5 I25 
# 5 8 I26 
# 6 11 I26 
# 7 12 I26 
# 8 13 I26 
# 9 3 I26 
# 10 3 I25 

index = which(b$id %in% a$id) 

b[index[which(b[index,]$code %in% "I25")],] 

# id code 
# 1 1 I25 
# 2 2 I25 
# 3 2 I25 
# 10 3 I25 

b[index[which(b[index,]$code %in% c("I25", "I26"))],] 

# id code 
# 1 1 I25 
# 2 2 I25 
# 3 2 I25 
# 6 11 I26 
# 7 12 I26 
# 8 13 I26 
# 9 3 I26 
# 10 3 I25 

#True |假

b$TF = rep(NA, nrow(b)) 

b$TF[index[which(b[index,]$code %in% c("I25", "I26"))]] <- 1 

b$TF[-(index[which(b[index,]$code %in% c("I25", "I26"))])] <- 0 

b 
# id code TF 
# 1 1 I25 1 
# 2 2 I25 1 
# 3 2 I25 1 
# 4 5 I25 0 
# 5 8 I26 0 
# 6 11 I26 1 
# 7 12 I26 1 
# 8 13 I26 1 
# 9 3 I26 1 
# 10 3 I25 1 
+0

看到我编辑的答案 – Sathish 2015-04-02 19:57:46

+0

看到,OP有“I25.11”和“I25.12”,而不仅仅是I25 – infominer 2015-04-02 19:59:11

+0

连接字符串进行匹配,如在b [其中(b $ code%in%c(“I25.11 “,”I25.12“)),]应该可以工作 – Sathish 2015-04-02 20:03:39

相关问题