MattCom MattCom - 2 months ago 20
R Question

sapply in r with user defined function

My code is as follows:

data("USArrests")

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)
}
k<-USArrests$UrbanPop
k

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
AssignLevel(k,q)
but not when I run in in sapply.

Answer

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

data("USArrests")

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)