0

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) 

5 Answers 5

3

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" 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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 } } 

Comments

1

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 

1 Comment

this is vectorized in appearance (hiding loops), but much less efficient than @EDi 's answer which uses truly vectorized operations, I believe using Vectorize on your own functions is not generally good practice
0

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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.