[英]How can i apply a function with an ifelse stricture
我做了一个新功能:
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)
}
当我测试功能时,它运作良好。 但是,当我将其应用于数据框时,它不起作用:
df <- as.data.frame(c("aa","cc","kk", "nn"))
df$new <- newFunction((df[,1]))
我希望得到“列表A”,“列表A”,“其他列表”,“其他列表”-但是我没有这种运气,而我留下的是“其他列表”,“其他列表”,“其他列表” ,“其他列表”
你可以尝试
sapply (df[,1], newFunction)
要么
map(df[,1], newFunction)
像这样做:
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)
}
现在它已被向量化,您可以执行df$new <- newFunction(df[,1])
,它的效率要高得多。
我强烈建议阅读此R-FAQ,以了解ifelse
与if(){}else{}
对比。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.