2014-10-07 40 views
3

我认为这只是一行简单的代码,但我的挑战的解决方案正在逃避我。我敢打赌,我对R编程领域的有限经验可能是源头。如何在r中的单元格中包含的字符串中返回包含关键字的行

数据集

df <- structure(list(Key_MXZ = c(1731025L, 1731022L, 1731010L, 1730996L,  
    1722128L, 1722125L, 1722124L, 1722123L, 1722121L, 1722116L, 1722111L,  
    1722109L), Key_Event = c(1642965L, 1642962L, 1647418L, 1642936L,   
    1634904L, 1537090L, 1537090L, 1616520L, 1634897L, 1634892L, 1634887L,  
    1634885L), Number_Call = structure(c(11L, 9L, 10L, 12L, 1L, 3L,    
    2L, 4L, 5L, 6L, 8L, 7L), .Label = c("3004209178-2010-04468",    
    "3004209178-2010-04469", "3004209178-2010-04470", "3004209178-2010-04471", 
    "3004209178-2010-04472", "3004209178-2010-04475", "3004209178-2010-04477", 
    "3004209178-2010-04478", "3004209178-2010-04842", "3004209178-2010-04850", 
    "I wish to return this row with the header", "Maybe this row will work too" 
    ), class = "factor")), .Names = c("Key_MXZ", "Key_Event", "Number_Call"  
    ), class = "data.frame", row.names = c("1", "2", "3", "4", "5",    
    "6", "7", "8", "9", "10", "11", "12")) 

在最后一栏我已经把将被用来识别一个新的数据帧中行的其它数据类型中两个字符串 - 使用短语“该行”。最终的结果可能是:

Key_MXZ|Key_Event|Number_Call 
1|1731025|1642965|I wish to return this row with the header 
4|1730996|1642936|Maybe this row will work too 

我已经试过的代码看不见收效甚微突破以下变化等。

txt <- c("this row") 
table1 <- df[grep(txt,df),] 
table2 <- df[pmatch(txt,df),] 
df[,3]<-is.logical(df[,3]) 
table3 <- subset(df,grep(txt,df[,3])) 

对此挑战有何想法?

回答

2

df[grep("this row", df$Number_Call, fixed=TRUE),] 

# Key_MXZ Key_Event        Number_Call 
#1 1731025 1642965 I wish to return this row with the header 
#4 1730996 1642936    Maybe this row will work too 

只需要引用您想grep来尝试匹配

固定= TRUE长相精确匹配实际列,和grep返回这些元素的indeces在列表中击中比赛。如果你的比赛有点细微差别,你可以用正则表达式代替“this row”

3

与DMTs的答案非常相似。下面使用data.table做法是快的情况下,你有几百万行:

setDT(df); setkey(df, Number_Call) 
df[grep("this row", Number_Call, ignore.case = TRUE)] 

    Key_MXZ Key_Event        Number_Call 
1: 1731025 1642965 I wish to return this row with the header 
2: 1730996 1642936    Maybe this row will work too 
3

下面是一个使用qdapSearch功能的方法。这是一个agrep的包装,所以它可以做模糊匹配和模糊程度可以设置:

library(qdap) 
Search(df, "this row", 3) 

## Key_MXZ Key_Event        Number_Call 
## 1 1731025 1642965 I wish to return this row with the header 
## 4 1730996 1642936    Maybe this row will work too 
+0

谢谢泰勒。我想知道你正在运行的是什么版本的R和OS。我在R 3.1.1/Win8上用qdap尝试了这种方法,并得到一条错误消息“loadNamespace中的错误”bc dplyr需要大于等于0.3版本。我曾尝试更新dplyr,但由于某些未知原因它仍然保持在.2。 – Aaron 2014-10-08 12:13:31

+0

嗯,那太臭了。我认为['dplyr'正在处理一些事情](http://cran.r-project.org/web/checks/check_results_dplyr.html)。您可以尝试在R -vanilla会话中运行'install.packages(“dplyr”,type =“source”)'(即dplyr未加载)。我正在运行Win7 R dev版本。但它看起来像'dplyr .3.0.1'在CRAN上,现在Windows的二进制文件将在几天内建成。我希望他们正在经历的一些纠结会被解决。如果你能够使用这种方法,你能否请更新我(即,安装qdap)。 – 2014-10-08 12:30:10

+0

我希望看到qdap的工作。所以,也许当我扩大我的代码我可能会再试一次? – Aaron 2014-10-08 16:29:59

相关问题