r - 如何在r中的单元格中包含的字符串中返回带有关键字的行

标签 r subset

我认为这将是简单的一行代码,但我无法解决我的挑战。我敢打赌,我在 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]))

对这个挑战有什么想法吗?

最佳答案

与 DMT 的答案非常相似。下面使用 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

关于r - 如何在r中的单元格中包含的字符串中返回带有关键字的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26246344/

相关文章:

r - 你可以在 R 中传递引用吗?

r - ggplot : change the order of stacked bars based on the a name within the bar

r - 在 ggplot2 中 - 如何确保 geom_errorbar 在使用 xlim() 控制 x 轴时显示所有点的条形限制

r - 在 R 中使用子集时如何忽略大小写

r - 如何通过选择列表中除一个值之外的所有元素来对 R 中的列表进行子集化?

sql - 按 ID 选择最近增加值列

arrays - 在 julia 中获取多维数组的一维子集

R计算一行而不是列的模式

r - 如何优化 R 中词干提取和拼写检查的性能?

R:数据框或列表列表中的部分(或完全)匹配