Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does R have a wildcard expression (such as an asterisk (*))?

Tags:

r

I hope I am not missing something obvious but here is my question:

Given data like this

Data1=
Name       Number
AndyBullxxx    12
AlexPullxcx    14
AndyPamxvb     56
RickRalldfg    34
AndyPantert    45
SamSaltedf     45

I would like to be able to pull out all of the rows starting with "Andy"

subset(Data1,Name=="Andy*")

AndyBullxxx  12
AndyPamxvb   56
AndyPantert  45

So basically a wild card symbol that will let me subset all rows that begin with a certain character designation.

like image 983
Vinterwoo Avatar asked Nov 17 '11 21:11

Vinterwoo


People also ask

What does the wildcard operator * do?

An asterisk (*) may be used to specify any number of characters. It is typically used at the end of a root word, when it is referred to as "truncation." This is great when you want to search for variable endings of a root word.


1 Answers

Try,

df[grep("^Andy",rownames(df)),]

the first argument of grep is a pattern, a regular expression. grep gives back the rows that contain the pattern given in this first argument. the ^ means beginning with.

Let's make this reproducible:

 df <- data.frame(x=c(12,14,56,34,45,45))
 rownames(df) <- c("AndyBullxxx", "AlexPullxcx","AndyPamxvb", "RickRalldfg","AndyPantert","SamSaltedf")
 ## see what grep does
 grep("^Andy",rownames(df))
like image 130
Matt Bannert Avatar answered Oct 06 '22 05:10

Matt Bannert