回答
如果您熟悉SQL語法,則可以使用aggregate
和merge
。 服用example from the PostgreSQL manual之一,我們將使用
empsalary <- data.frame(depname=rep(c("develop", "personnel", "sales"), c(5, 2, 3)),
empno=c(11, 7, 9, 8, 10, 5, 2, 3, 1, 4),
salary=c(5200, 4200, 4500, 6000, 5200, 3500, 3900, 4800, 5000, 4800))
merge(empsalary, aggregate(salary ~ depname, empsalary, mean), by="depname")
再現第一實施例(通過depname
計算平均工資)。
depname empno salary.x salary.y
1 develop 11 5200 5020.000
2 develop 7 4200 5020.000
3 develop 9 4500 5020.000
4 develop 8 6000 5020.000
5 develop 10 5200 5020.000
6 personnel 5 3500 3700.000
7 personnel 2 3900 3700.000
8 sales 3 4800 4866.667
9 sales 1 5000 4866.667
10 sales 4 4800 4866.667
您可能想要看看plyr必須提供更詳細的結構。
正確,上面的解決方案創建一個新的data.frame。你也可以模擬合併,如下所示:'m < - with(empsalary,rep(tapply(salary,depname,mean),table(depname)))'','cbind'在你的原始data.frame中生成的向量。例如,對於平均PERC。的工資,我們可以使用'empsalary $ avg.perc < - empsalary $ salary/m * 100'。 – chl
謝謝你的回覆。假設我想用R語言解決以下查詢: SELECT depname,empno,(salary * avg(salary)OVER(PARTITION BY depname))* 100,(cost * avg(cost)OVER(PARTITION BY depname))* 100 FROM empsalary 然後,我是否需要編寫一個單獨的合併併爲每個窗口函數創建一個臨時數據框併合並所有最終結果..? –
不是。您可以使用我提出的建議(按組計算均值並按行擴展,然後將其作爲新列添加到您的data.frame中);您只需添加第二個聚合步驟,用'cost'替換'salary'。 (順便說一句,*不要刪除您的評論*,否則未來的讀者將無法關注對話。) – chl
- 1. R中的窗口函數?
- 2. R:窗口()函數
- 3. R中的滑動窗口函數
- 4. SQL Server - 窗口函數
- 5. SQL Server 2014中的窗口函數
- 6. 中的R語言
- 7. 在SQL Server中嵌套窗口函數
- 8. R中函數的語法?
- 9. 有條件的窗口函數sql
- 10. 情節中的R語言
- 11. SVM中的R語言
- 12. 瞭解pryr軟件包(R語言)中partial()函數的代碼?
- 13. R語言中rdivide(matlab)的等效函數
- 14. r data.table語言中的函數式編程/元編程/計算
- 15. 窗口函數執行一個SQL查詢語句
- 16. 在R語言
- 17. 執行SQL與「象」語句中的R語言
- 18. 窗口與屏幕設計語言
- 19. 找出語言窗口被安裝爲
- 20. 爲窗口綁定C語言
- 21. SQL查詢(窗口函數)協助
- 22. SQL窗口函數與where子句
- 23. spark SQL窗口函數滯後
- 24. Spark,Hive SQL - 實現窗口函數?
- 25. 使用語言集成SQL的schemaRDD的SQL函數
- 26. 數據框中的滑動窗口r
- 27. R中的移動窗口
- 28. 如何提取函數內部使用R語言的函數參數?!
- 29. R emacs窗口
- 30. 含義R語言
嗨。你需要一個例子來展示你用window postegre sql函數做了什麼。 – agstudy