简体   繁体   English

我怎样才能将函数应用得狭窄

[英]How can i apply a function with an ifelse stricture

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" 我希望得到“列表A”,“列表A”,“其他列表”,“其他列表”-但是我没有这种运气,而我留下的是“其他列表”,“其他列表”,“其他列表” ,“其他列表”

You could try either 你可以尝试

sapply (df[,1], newFunction)

or 要么

map(df[,1], newFunction)

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. 现在它已被向量化,您可以执行df$new <- newFunction(df[,1]) ,它的效率要高得多。

I'd strongly recommend reading this R-FAQ to understand ifelse vs if(){}else{} . 我强烈建议阅读此R-FAQ,以了解ifelseif(){}else{}对比。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM