2012-04-09 49 views
4

我的data.framerow.names一樣在測試中。根據字符串選擇data.frame中的行

test <- 
c("Env_1990:trait_KPS", "Env_1990:trait_SPSM", "Env_1990:trait_TKW", 
"Env_1990:trait_Yield", "Env_1991:trait_KPS", "Env_1991:trait_SPSM", 
"Env_1991:trait_TKW", "Env_1991:trait_Yield", "Env_1992:trait_KPS", 
"Env_1992:trait_SPSM", "Env_1992:trait_TKW", "Env_1992:trait_Yield", 
"Env_1993:trait_KPS", "Env_1993:trait_SPSM", "Env_1993:trait_TKW", 
"Env_1993:trait_Yield", "Env_1994:trait_KPS", "Env_1994:trait_SPSM", 
"Env_1994:trait_TKW", "Env_1994:trait_Yield", "Env_1995:trait_KPS", 
"Env_1995:trait_SPSM", "Env_1995:trait_TKW", "Env_1995:trait_Yield", 
"Gen_B88:Env_1990:trait_KPS", "Gen_B88:Env_1990:trait_SPSM", 
"Gen_B88:Env_1990:trait_TKW", "Gen_B88:Env_1990:trait_Yield", 
"Gen_B88:Env_1991:trait_KPS", "Gen_B88:Env_1991:trait_SPSM", 
"Gen_B88:Env_1991:trait_TKW", "Gen_B88:Env_1991:trait_Yield", 
"Gen_B88:Env_1992:trait_KPS", "Gen_B88:Env_1992:trait_SPSM", 
"Gen_B88:Env_1992:trait_TKW", "Gen_B88:Env_1992:trait_Yield", 
"Gen_B88:Env_1993:trait_KPS", "Gen_B88:Env_1993:trait_SPSM", 
"Gen_B88:Env_1993:trait_TKW", "Gen_B88:Env_1993:trait_Yield") 

我想只選擇那些以Env_開頭的行。我想這個代碼R

grep(pattern="[Env_]", x=test). 

此代碼給了我所有的行,因爲Env_出現在每一行的名字。我想知道如何選擇僅以Env_開頭的行。在此先感謝您的幫助。

+0

[Env_]是一個字符類。它匹配任何包含任何單個字符E,n,v或_的字符串。 – 2012-04-09 05:22:01

回答

12

您要添加的^字符起跑線/串的:

> grep("^Env_", test) 
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
> grep("^Env_", test, value = TRUE) 
[1] "Env_1990:trait_KPS" "Env_1990:trait_SPSM" "Env_1990:trait_TKW" 
[4] "Env_1990:trait_Yield" "Env_1991:trait_KPS" "Env_1991:trait_SPSM" 
[7] "Env_1991:trait_TKW" "Env_1991:trait_Yield" "Env_1992:trait_KPS" 
[10] "Env_1992:trait_SPSM" "Env_1992:trait_TKW" "Env_1992:trait_Yield" 
[13] "Env_1993:trait_KPS" "Env_1993:trait_SPSM" "Env_1993:trait_TKW" 
[16] "Env_1993:trait_Yield" "Env_1994:trait_KPS" "Env_1994:trait_SPSM" 
[19] "Env_1994:trait_TKW" "Env_1994:trait_Yield" "Env_1995:trait_KPS" 
[22] "Env_1995:trait_SPSM" "Env_1995:trait_TKW" "Env_1995:trait_Yield" 
+0

感謝您的不錯和有益的答案。如果你還讓我知道如何選擇Env_出現在中間的那些行,我將不勝感激。謝謝 – MYaseen208 2012-04-09 00:50:10

+0

很高興幫助。對於那些中間的「Env_」,看起來它們總是在':'之後出現,所以你的模式可能是「:Env_」。與任何字符後面的「Env_」匹配的更一般的模式是「。+ Env_」。 – flodel 2012-04-09 00:58:09

相關問題