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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.