使用.SD进行data.table操作:简明地计算百分比变化

时间:2015-03-14 23:44:45

标签: r data.table

我试图使用data.table简洁地计算一些百分比变化,但我完全理解.SD操作是如何工作的。

我们说我有下表

dt = structure(list(type = c("A", "A", "A", "B", "B", "B"), Year = c(2000L, 
2005L, 2010L, 2000L, 2005L, 2010L), alpha = c(0.0364325563237498, 
0.0401968159729988, 0.0357395587861466, 0.0317236054181487, 0.0328213742235379, 
0.0294694430578336), beta = c(0.0364325563237498, 0.0401968159729988, 
0.0357395587861466, 0.0317236054181487, 0.0328213742235379, 0.0294694430578336
)), .Names = c("type", "Year", "alpha", "beta"), row.names = c(NA, 
-6L), class = c("data.table", "data.frame"))


> dt
##    type Year      alpha       beta
## 1:    A 2000 0.03643256 0.03643256
## 2:    A 2005 0.04019682 0.04019682
## 3:    A 2010 0.03573956 0.03573956
## 4:    B 2000 0.03172361 0.03172361
## 5:    B 2005 0.03282137 0.03282137
## 6:    B 2010 0.02946944 0.02946944

要按类别计算alpha的百分比变化,我想出了以下代码:

dt[,change:=list(lapply(3:2,function(x)(.SD[x,alpha]/.SD[
(x-1),alpha]))),by=list(type)][][Year==2000,change:=NA]   

但有些事情告诉我他们可能会采用更简洁的方式。特别是如果想要对两列执行百分比更改,则以下操作无效

dt[,c("changeAlpha","changeBeta"):=list(lapply(3:2,
function(x)(.SD[x]/.SD[(x-1)]))),by=list(type)][Year==2000,change:=NA][]

所以我求助于:

dt[,c("changeAlpha","changeBeta"):=list(
lapply(3:2,function(x)(.SD[x,alpha]/.SD[(x-1),alpha])),
lapply(3:2,function(x)(.SD[x,beta]/.SD[(x-1),beta]))),by=list(type)][
Year==2000,c("changeAlpha","changeBeta"):=list(NA,NA)][]

##        type Year      alpha       beta       changeAlpha        changeBeta
## 1:    A 2000 0.03643256 0.03643256                NA                NA
## 2:    A 2005 0.04019682 0.04019682  1.10332131557826  1.10332131557826
## 3:    A 2010 0.03573956 0.03573956 0.889114172877617 0.889114172877617
## 4:    B 2000 0.03172361 0.03172361                NA                NA
## 5:    B 2005 0.03282137 0.03282137  1.03460416276522  1.03460416276522
## 6:    B 2010 0.02946944 0.02946944 0.897873527693412 0.897873527693412

但是操作似乎是对的,但是有很多警告引导我到这里来。

  • 我的思维方式是完全错误还是正确的方法来进行此操作?

1 个答案:

答案 0 :(得分:9)

您可以使用data.table v1.9.6 +

中的shift函数

定义你的功能

myFunc <- function(x) x/shift(x)

选择要计算

百分比的列
cols <- c("alpha", "beta")

或者,如果你想在所有上运行这个,除了前两个

cols <- names(dt)[-(1:2)]

在列上运行该功能

dt[, paste0("change", cols) := lapply(.SD, myFunc), by = type, .SDcols = cols][]
#    type Year      alpha       beta changealpha changebeta
# 1:    A 2000 0.03643256 0.03643256          NA         NA
# 2:    A 2005 0.04019682 0.04019682   1.1033213  1.1033213
# 3:    A 2010 0.03573956 0.03573956   0.8891142  0.8891142
# 4:    B 2000 0.03172361 0.03172361          NA         NA
# 5:    B 2005 0.03282137 0.03282137   1.0346042  1.0346042
# 6:    B 2010 0.02946944 0.02946944   0.8978735  0.8978735