0
多個約束在數據表上執行操作正常,當我在數據表上執行操作的一個約束e.g基於R中
setDT(df)[, mean.price := mean(Price), by = Id]
這個命令得到價格的基礎上獨一無二的Id
的平均值。我的問題是,如果有一種方法來提在命令兩個約束e.g
setDT(df)[, mean.price := mean(Price), by = Id & Year]
所以我可以得到相同的Id
行屬於同一Year
的平均值。
假設我有以下數據幀
Id Price Year
1 5 2003
1 10 2003
1 4 2003
1 6 2004
1 6 2004
1 10 2004
2 7 2003
2 10 2003
2 3 2003
2 2 2004
2 3 2004
2 10 2004
所以得到的數據幀將看起來像
Id Price Year Mean.Price
1 5 2003 6.33
1 10 2003 6.33
1 4 2003 6.33
1 6 2004 7.33
1 6 2004 7.33
1 10 2004 7.33
2 7 2003 7
2 10 2003 7
2 4 2003 7
2 2 2004 5
2 3 2004 5
2 10 2004 5
我想你需要'setDT(df)[,Mean.Price:= mean(Price),by =。(Id,Year)]'如果你想指定'names',即'setDT(df) [,Mean.Price:= mean(Price),c(names(df)[c(1,3)])]' – akrun
您是否閱讀過'?data.table'?這種操作有很多例子 –