Friday, September 8, 2017

Learn R: Common character functions you need to know

   
      R comes with many built-in functions, I am going to cover the most common built-in character functions you might use daily in this post. These functions are coming with the base package and you do not need to add/install any packages to use them.

How to get substring of a text?

substr(txt, start, end)

text <- 'Today is a great day to learn R'
firstfive <- substr(text,1,5)
firstfive
[1] "Today"
> 

How to convert string to upper or lower cases?
 
toupper(txt)
tolower(txt)
 
[text <- 'Today is a great day to learn R'
toupper(text)
tolower(text)
[[1] "TODAY IS A GREAT DAY TO LEARN R"
[1] "today is a great day to learn r"
>

How to split string and create a list?
 
strsplit(text, character)
 
[text <- 'Today is a great day to learn R'
list <- strsplit(text,' ')
class(list)
[[1] "Today" "is"    "a"     "great" "day"   "to"    "learn" "R"   
[1] "list"
> 

How to convert list to array/vector?
 
unlist(obj)
 
[text <- 'Today is a great day to learn R'
list <- strsplit(text,' ')
arr <- unlist(list)
print(arr)
[[1] "Today" "is"    "a"     "great" "day"   "to"    "learn" "R" 
> 

How to seach in array?
 
grep(pattern, object, ignore.case=False, fixed=False)
Fixed argument needs to be False if you want to use regex pattern
 
[text <- 'Today is a great day to learn R'
list <- strsplit(text,' ')
arr <- unlist(list)
grep('day', arr, fixed=T)
[[1] 1 5 
> 

How to replace item/s in an array?
 
sub(pattern, replacement, target, ignore.case=False, fixed=False)
Fixed argument needs to be False if you want to use regex pattern
 
text <- 'Today is a great day to learn R'
sub('a great', 'the', text)
[[1] "Today is the day to learn R" 
> 

How to Concatenate strings?
paste(obj, sep="")
 
text <- 'Today is a great day to learn R'
list <- strsplit(text,' ')
arr <- unlist(list)
paste(arr,' ', sep=' ')
paste('Today is', date())
[[1] "Today  " "is  "    "a  "     "great  " "day  "   "to  "    "learn  "
[8] "R  "    
[1] "Today is Fri Sep  8 12:55:01 2017"
> 

No comments:

Post a Comment