Ntile and decile function depended on two columns in R [duplicate]

社会主义新天地 提交于 2019-12-25 02:58:50

问题


I would like to have a new column with Ntile but it should depend on column 1 - "year" and show the ntile number for column 2 - "mileage".

  year mileage
  <dbl>   <dbl>
1  2011    7413
2  2011   10926
3  2011    7351
4  2011   11613
5  2012    8367
6  2010   25125

mydata$Ntile <- ntile(mydata$mileage, 10)

I know the easy to use function ntile, but I do not know how to make it depend on 2 columns. I would like to have ntiles for mileage but for each year, 2010, 2011 and 2012 to be calculated in new column "Ntile".

PS: I know there is not enough data to calculate Ntiles for 2011 and 2012, it is just an example.


回答1:


I like the data.table approach:

library(data.table)
mydata <- as.data.table(mydata)
mydata[, Ntile:=ntile(mileage,10), by=year]

Best!



来源:https://stackoverflow.com/questions/54400557/ntile-and-decile-function-depended-on-two-columns-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!