Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subset vector by first letter in R

Tags:

r

I am working in R and I have a character vector. I would like to subset this vector by the first letter of the string of characters. So, for example, how can I subset the vector to return only those elements in the vector that start with the letter A?

like image 489
Pascal Avatar asked Apr 20 '11 01:04

Pascal


People also ask

How do you subset a character vector in R?

The way you tell R that you want to select some particular elements (i.e., a 'subset') from a vector is by placing an 'index vector' in square brackets immediately following the name of the vector. For a simple example, try x[1:10] to view the first ten elements of x.

How do you subset an object in R?

Method 2: Subsetting in R Using [[ ]] Operator [[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.

How do I index a vector in R?

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1. To get the 7th element of the colors vector: colors[7] .

How do I extract a character from a string in R?

substring() function in R Programming Language is used to extract substrings in a character vector. You can easily extract the required substring or character from the given string.


2 Answers

you can use grep:

vector = c("apple", "banana", "fox", "Actor")
vector[grep("^[aA].*", vector)]

[1] "apple" "Actor"
like image 118
Greg Avatar answered Oct 03 '22 23:10

Greg


You could also use substr with tapply to get a list of all types:

tapply(vector,toupper(substr(vector,1,1)),identity)

$A
[1] "apple" "Actor"

$B
[1] "banana"

$F
[1] "fox"
like image 26
James Avatar answered Oct 03 '22 22:10

James