我的代码如下所示:
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))
我试图将每个州的城市人口值更改为对应四分位数之一。当我运行
AssignLevel(k,q)
时有效,但在sapply中运行时无效。
aye: cut(USArrests$UrbanPop, breaks=c(min(USArrests$UrbanPop), q, max(USArrests$UrbanPop)), labels=c("LOW", "MODERATE", "HIGH", "VERY HIGH"), include.lowest=TRUE)
更加简洁。 - hrbrmstr