zjffdu
zjffdu

Reputation: 28734

How to vectorize my function in R?

I write a function in R as following, but I could not use it in a vectorize way (the second part of the code below). I am wondering how can I make this function vectorize

normalize=function(browser){
   if (browser=="Chrome" | browser=="Firefox" | browser=='Safari' | grepl('IE',browser)){
     browser
   }else{
     "Others"
   }
}

data$browser_n<-normalize(data$browser)      // not working (data is a data frame) 

Upvotes: 0

Views: 171

Answers (5)

CHP
CHP

Reputation: 17189

While this may not be most correct answer, you can try Vectorize. In general, you can use Vectorize on many functions to vectorize them. I should add that Vectorize is just a pretty wrapper around mapply

normalize = function(browser) {
    if (browser == "Chrome" | browser == "Firefox" | browser == "Safari" | grepl("IE", browser)) {
        return(browser)
    } else {
        return("Others")
    }
}

vNormalize <- Vectorize(normalize)

data <- data.frame(browser = c("Chrome", "Firefox", "Safari", "IE 10"))

vNormalize(data$browser)
## [1] Chrome  Firefox Safari  IE 10  
## Levels: Chrome Firefox IE 10 Safari

Upvotes: 1

Ramnath
Ramnath

Reputation: 55685

Here are two comments.

It would be better to use || instead of |. Here is why.

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

Another approach would be to use any.

 normalize = function(browser){
   if (any(browser == "Chrome", browser == "Firefox", browser == "Safari",
     grepl("IE", browser)) {
     browser
   } else {
     "Others
   }
 }

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

normalize <- function(browser){
  replace(browser, !(browser %in% c("Chrome", "Firefox", "Safari") | 
                     grepl('IE',browser)), "Others")  
}

Upvotes: 2

Jouni Helske
Jouni Helske

Reputation: 6477

Or, if you are not really interested in vectorization, but want to get the new variable browser_n as in your example, you could just write

data$browser_n<-data$browser
data$browser_n[!(data$browser=="Chrome" | data$browser=="Firefox" | 
               data$browser=='Safari' | grepl('IE',data$browser))] <- "Others"

Upvotes: 0

EDi
EDi

Reputation: 13280

Use ifelse():

normalize=function(browser){
  ifelse(browser=="Chrome" | browser=="Firefox" | browser=='Safari' | grepl('IE',browser), browser, 'Others')
}

browser <- c('aaa', 'Chrome')
normalize(browser) 
# [1] "Others" "Chrome"

Upvotes: 3

Related Questions