Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting rows in data.frame based on character strings

Tags:

r

I've a data.frame with row.names as in test.

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")

I want to select only those rows which start with Env_. I tried this code in R

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

This code gives me all rows because Env_ appears in every row name. I wonder how to select rows which starts only with Env_. Thanks in advance for your help.

like image 427
MYaseen208 Avatar asked Apr 09 '12 00:04

MYaseen208


People also ask

How do you select rows of pandas DataFrame based on values in a list?

isin() to Select Rows From List of Values. DataFrame. isin() method is used to filter/select rows from a list of values. You can have the list of values in variable and use it on isin() or use it directly.


1 Answers

You want to add the ^ character for beginning of line/string:

> 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"
like image 151
flodel Avatar answered Sep 22 '22 11:09

flodel