Ntile和十分位函数取决于R中的两列 [英] Ntile and decile function depended on two columns in R

查看:99
本文介绍了Ntile和十分位函数取决于R中的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Ntile中增加一个新列,但该列应取决于第1列-年份",并显示第2列的Ntile编号-里程".

  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)

我知道易于使用的函数ntile,但是我不知道如何使它依赖于2列.我想使用ntiles作为里程数,但要在新列"Ntile"中计算2010、2011和2012年的年增长率.

PS:我知道没有足够的数据来计算2011和2012年的Ntiles,这只是一个例子.

解决方案

我喜欢data.table方法:

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

最好!

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.

解决方案

I like the data.table approach:

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

Best!

这篇关于Ntile和十分位函数取决于R中的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆