MattCom MattCom - 1 year ago 98
R Question

sapply in r with user defined function

My code is as follows:


AssignLevel <- function(p,quartiles)
if (p < quartiles[1])
rlevel <-"LOW"
else if (p < quartiles[2])
rlevel <-"MODERATE"
else if (p < quartiles[3])
rlevel <-"HIGH"
else level <-"VERY HIGH"
return (rlevel)

q<- quantile(USArrests$UrbanPop, c(.25,.5,.75))

newCol <- sapply(USArrests$UrbanPop,AssignLevel(k,q))

I'm trying to change the value of every state's urban pop value into one of the corresponding quartiles. It works when I run
but not when I run in in sapply.

Answer Source

I agree that the cut solution is better. For fun, here is how to resolve your current issue:


AssignLevel <- function(p,quartiles) {
  if (p < quartiles[[1]]){
    rlevel <- "LOW"
  } else if(p < quartiles[[2]]) {
    rlevel <- "MODERATE"
  } else if(p < quartiles[[3]]) {
    rlevel <- "HIGH"
  } else {
    rlevel <- "VERY HIGH"
  return (rlevel)
k <- USArrests$UrbanPop

q <- quantile(k, c(.25,.5,.75))

newCol <- sapply(k,AssignLevel,q)