2016-09-19 35 views
1

我有一个数据框,其中包含两种类型的列和带有名称的向量。 如何选择数据框中的某些行与矢量字符串匹配。匹配数据框中的字符串向量中的模式

name = c("[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]") 
expression = c(118.84, 90.04, 106.6, 104.99, 93.2, 66.84, 90.02, 108.03, 111.83) 
dataset <- as.data.frame(cbind(name, expression)) 
nam <- c("HPS5", "HPS6", "HPS9", "HPS2") 

函数应该返回日期仅框架规定的线路 我尝试 dataset[mapply(grepl,nam,dataset$name)] 但它没有工作

回答

1

我们可以在“南”使用pastecollapse,用它作为pattern论点grep,得到指数和子集 '数据集'

dataset[grep(paste(nam, collapse="|"), dataset$name),] 

如果我们使用OP的代码,将'name'列包装在list内,否则mapply将会经历'name'的各个元素,并且由于'name'和'nam'中的数字元素不同, ,这会引发关于longer argument not a multiple of length of shorter的警告。 mapply将返回一个逻辑矩阵,我们从该矩阵中取出rowSums并检查它是否大于0以获取子集化行的逻辑向量。

dataset[rowSums(mapply(grepl, nam, list(dataset$name)))>0,]