Learning R data types – Vector (char)

A vector can be used to store strings as well.

R Vector is different from a database column

In the prior post, I mentioned that a R vector is like a column in a database table.  However, it is not exactly true. Here is why:

The value in a R vector can be referred like referring a value in an array.

> a=c("I have dream","I do not like it", "oh my god","thank you")
> a[3]
[1] "oh my god"

In this example, we can directly retrieve a value in a column by its location.  In other word, R stores the values in a vector in order.  We can loop through the values like manipulating a Vector in Java.

Correct an element in a vector

> a[1]="I have a dream"
> a
[1] "I have a dream" "I do not like it" "oh my god" "thank you"

Add an element into a vector

> length(a)
[1] 4
> a[5]="You are welcome"
> length(a)
[1] 5
> a
[1] "I have a dream" "I do not like it" "oh my god" "thank you"
[5] "You are welcome"

But how to insert an element?

Append seems a better way!

> append(a,"good bye",3)
[1] "I have a dream" "I do not like it" "oh my god" "good bye"
[5] "thank you" "You are welcome"
> length(a)
[1] 5
> a
[1] "I have a dream" "I do not like it" "oh my god" "thank you"
[5] "You are welcome"
> a=append(a,"good bye",3)
> length(a)
[1] 6
> a
[1] "I have a dream" "I do not like it" "oh my god" "good bye"
[5] "thank you" "You are welcome"

Search a string (similar to the LIKE filter)

> a=c("I have dream","I do not like it", "oh my god","thank you")
> grep("I", a)
[1] 1 2
> grep("my", a)
[1] 3
> grep("you", a)
[1] 4
> a[grep("I",a)]
[1] "I have dream" "I do not like it"

This statement is similar to issue a LIKE query.

SELECT X
FROM LIST_TBL
WHERE X LIKE '%I%'

How about concatenating and taking a substring?

Leave a comment