O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

To exploit vectorized operations, follow these steps:

  1. Operate on all elements of vectors without explicit iteration (vectorized operations):
> first.name <- c("John", "Jane", "Tom", "Zach") 
> last.name <- c("Doe", "Smith", "Glock", "Green") 
> # The paste function below operates on vectors 
> paste(first.name,last.name) 
 
[1] "John Doe"   "Jane Smith" "Tom Glock"  "Zach Green" 
 
> # This works even with different sized vectors 
> new.last.name <- c("Dalton") 
> paste(first.name,new.last.name) 
 
[1] "John Dalton"   "Jane Dalton"  "Tom Dalton"  "Zach  Dalton"
  1. Use vectorized operations within your own functions:
> username <- function(first, last) { tolower(paste0(last, substr(first,1,1))) } > username(first.name,last.name) [1] "doej" "smithj" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required