2016-09-19 85 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,]