Reputation: 376
I make a new function:
newFunction <- function (varX) {
lst_a <- c("aa", "bb", "cc")
lst_b <- c("dd", "ee", "ff")
lst_c <- c("gg", "hh", "ii")
ifelse(varX %in% lst_a , x.out <- "List A" , x.out <- "Other List" )
ifelse(varX %in% lst_b , x.out <- "List B" , x.out )
ifelse(varX %in% lst_c , x.out <- "List C" , x.out)
return(x.out)
}
When I test the function it works well. But when I apply it to a dataframe it does not work:
df <- as.data.frame(c("aa","cc","kk", "nn"))
df$new <- newFunction((df[,1]))
I expected to get "List A", "List A", "Other list", "Other List" - but no such luck have I, and left with me is "Other list", "Other List", "Other list", "Other List"
Upvotes: 0
Views: 58
Reputation: 145785
Do it like this:
newFunction <- function (varX) {
lst_a <- c("aa", "bb", "cc")
lst_b <- c("dd", "ee", "ff")
lst_c <- c("gg", "hh", "ii")
x.out = ifelse(varX %in% lst_a , "List A" ,
ifelse(varX %in% lst_b , "List B",
ifelse(varX %in% lst_c , "List C" , "Other List")))
return(x.out)
}
Now it is vectorized and you can do df$new <- newFunction(df[,1])
and it is much more efficient.
I'd strongly recommend reading this R-FAQ to understand ifelse
vs if(){}else{}
.
Upvotes: 1
Reputation: 179
You could try either
sapply (df[,1], newFunction)
or
map(df[,1], newFunction)
Upvotes: 1