2017-02-23 49 views
0

我有一个数据集,在其短暂的版本是这样的:从列查找字符串精确匹配

> df 
V1   V2 
MID_R  1.243879014 
MID   2.238147196 
MID_Rcon 0.586581997 
MID_U  0.833624164 
MID   -0.681462038 
MID   -0.593624936 
MID_con  0.060862707 
MID_con  -0.764524044 
MID_R  -0.128464132 

我写了一个代码只选择MID行和calcualte的手段为他们:

MID_match <- c("MID^") # choosing specific pattern to search through conditions 
MID <- df[grepl(paste(MID_match, collapse="|"), df$V1), ] # grouping across this pattern 
MID$V2 <- as.numeric(as.character(MID$V2)) 
mean_MID <- mean(MID$V2) # calculating mean 
MID_mean = rbind(MID_mean, data.frame(mean_MID)) 

,我瞄准的第一和第二行应该是这样的输出:

> MID_match 
    [1] "MID" 

> MID 
    V1   V2 
MID   2.238147196 
MID   -0.681462038 
MID   -0.593624936 

不过,我让所有组成字符串MID,例如初始数据集的行:

> MID 

V1   V2 
MID_R  1.243879014 
MID   2.238147196 
MID_Rcon 0.586581997 
MID_U  0.833624164 
MID   -0.681462038 
MID   -0.593624936 
MID_con  0.060862707 
MID_con  -0.764524044 
MID_R  -0.128464132 

我尝试使用grep的功能,但它didnt'work:

MID_match <- df$V1(grep("\\bMID\\b", df$V1)) 

任何想法如何提取确切的MID值?

回答

1

我想我dind't赶上好你的问题,但如果你的目标是只选择MID行,那么你可以用这个做到:

> df[grepl("^MID$", as.character(df$V1)), ] 
    V1   V2 
2 MID 2.2381472 
5 MID -0.6814620 
6 MID -0.5936249 
+0

似乎'=='应该在这种情况下工作,或者'%in%'为OP刚才请求的扩展。 – Frank

1

不要使用字符串搜索在这里,使用比较:

df[df$V1 == 'MID', ] 

这样会更有效一些,代码更少。

+0

非常感谢!完美地工作! – MariKo