R-从数据集中波士顿住房数据集找到1个观测值的所有特征的百分位数

问题描述

我正在研究Boston Housing数据集。我过滤了具有最低“ medv”的观测值(城镇),并在将其转换为新数据框后将其保存。我想在此新数据框中插入一列,其中包含基于原始数据的百分位,以用于这些过滤后的观察值的特征值。 这是R代码:

# load the library containing the dataset
library(MASS)

# save the data with custom name
boston = Boston

# suburb with lowest medv
low.medv = data.frame(t(boston[boston$medv == min(boston$medv),]))
low.medv

enter image description here

# The values I want populated in new columns:

# Finding percentile rank for crim
ecdf(boston$crim)(38.3518)
# >>> 0.9881423
ecdf(boston$crim)(67.9208)
# >>> 0.9960474

# percentile rank for lstat
ecdf(boston$lstat)(30.59)
# >>> 0.9782609
ecdf(boston$lstat)(22.98)
# >>> 0.8992095

所需的输出

enter image description here

是否可以通过sapply使用ecdf函数?

解决方法

如果您不事先转置数据,我认为这会更容易:

low.medv <- boston[boston$medv == min(boston$medv),]
res <- mapply(function(x,y) ecdf(x)(y),boston,low.medv)
res
#       crim     zn  indus   chas    nox      rm age     dis rad
#[1,] 0.9881 0.7352 0.8874 0.9308 0.8577 0.07708   1 0.05731   1
#[2,] 0.9960 0.7352 0.8874 0.9308 0.8577 0.13636   1 0.04150   1
#        tax ptratio  black  lstat     medv
#[1,] 0.9901  0.8893 1.0000 0.9783 0.003953
#[2,] 0.9901  0.8893 0.3498 0.8992 0.003953

现在,如果您想要4列中所示的结果,则可以:

cbind(t(low.medv),t(res))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...