2017-09-15 65 views
0

我有一個很大的數據框,有22列。我想根據第二列中的值進行過濾,因此如果該值不以「X」開頭,我想刪除該行。此外,如果第二列中的此值包含星號,我想刪除該行。根據起始字母和列中的星號進行篩選

test <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) 
secondcolumn <- c("Xidfhsfd*isjdf", "Hsuhdfskdh", "Xwidfsoid", "X*sdkfjjhsd", "Xkdsfhsd", "Uskesfudhsk", "Sdfukhsdiu", "Osdfihsdoiuh", "Xsodifdsifj") 
othercolumn <- c(3, 5, 7,2, 5, 8, 3, 0, 5) 

df <- as.data.frame(test, secondcolumn, othercolumn) 

這將如何完成?在這個例子中,我想刪除第1,2,4,6,7,8和9行。

謝謝!

回答

2

希望這個作品

# Condition 1: value start with "X" 
cond1 <- grep("^X", d[, 2]) 
# Condition 2: doesn't contain "*" 
cond2 <- grep("\\*", d[, 2], invert = TRUE) 
# Rows where any of condition is true 
wantedRows <- intersect(cond1, cond2) 
# Table without those rows 
d[wantedRows, ] 

enter image description here

+0

我可能一直不清楚,但我希望它以X開頭。有些值是NA,所以我認爲從X開始它會自動刪除它們。這將如何完成? –

0

另一種選擇是在字符串的開頭(^),其次是不在一個或多個字符匹配「X」的*[^*]+ )直到字符串的結尾($)以得到數字索引和基於該數字索引的子集行

df[grep("^X[^*]+$", df$secondcolumn),] 
# test secondcolumn othercolumn 
#3 3 Xwidfsoid   7 
#5 5  Xkdsfhsd   5 
#9 9 Xsodifdsifj   5