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?
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.
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.
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] .
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.
you can use grep:
vector = c("apple", "banana", "fox", "Actor")
vector[grep("^[aA].*", vector)]
[1] "apple" "Actor"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With