我有一個真正的大問題。我正在使用 RSTUDIO,我的任務是找到前一天平均價格的百分比變化。
創建了一個新列 PercantageCh,我可以自己添加值
bitcoin$PercentageCh[3] <- round((bitcoin$AverageP[3]-bitcoin$AverageP[2])/bitcoin$AverageP[2]*100, 3)
如何為所有 2014 行自動化此程序?謝謝

uj5u.com熱心網友回復:
你可以這樣做diff:
c(NA, diff(bitcoin$AverageP)) / bitcoin$AverageP
# [1] NA 0.004805676 -0.011046667 0.005965718
c(NA, diff(bitcoin$AverageP) / bitcoin$AverageP[-nrow(bitcoin)])
# [1] NA 0.004828882 -0.010925971 0.006001521
(使用馬特的bitcoin定義)。
使用哪個版本取決于它是相對于前一個值還是下一個值的百分比變化。(注意括號和 -/運算子下的內容,兩者之間是不同的。)
uj5u.com熱心網友回復:
嘗試使用dplyr::lag,
bitcoin$PercentageCh <- round((bitcoin$AverageP-lag(bitcoin$AverageP))/lag(bitcoin$AverageP)*100, 3)
我的位置錯了 lag
dlpyr::lag和之間的區別stats::lag
bitcoin <- data.frame(
AverageP = rnorm(10)
)
bitcoin$PercentageCh <- round((bitcoin$AverageP-dplyr::lag(bitcoin$AverageP))/dlpyr::lag(bitcoin$AverageP)*100, 3)
bitcoin
AverageP PercentageCh
1 2.1972088 NA
2 1.4049739 -36.056
3 0.5074163 -63.884
4 -1.4304888 -381.916
5 0.1726630 -112.070
6 -0.9722128 -663.070
7 -0.1076338 -88.929
8 1.1585936 -1176.421
9 -0.2636449 -122.756
10 -1.5825011 500.240
bitcoin$PercentageCh <- round((bitcoin$AverageP-stats::lag(bitcoin$AverageP))/stats::lag(bitcoin$AverageP)*100, 3)
bitcoin
AverageP PercentageCh
1 2.1972088 0
2 1.4049739 0
3 0.5074163 0
4 -1.4304888 0
5 0.1726630 0
6 -0.9722128 0
7 -0.1076338 0
8 1.1585936 0
9 -0.2636449 0
10 -1.5825011 0
uj5u.com熱心網友回復:
使用樣本資料:
bitcoin <- data.frame(AverageP = c(431.8805, 433.9660, 429.2245, 431.8005))
使用自定義函式:
pct_change <- function(x){
round((x - dplyr::lag(x))/dplyr::lag(x)*100,3)
}
bitcoin$PercentageCh <- pct_change(bitcoin$AverageP)
給我們:
AverageP PercentageCh
1 431.8805 NA
2 433.9660 0.483
3 429.2245 -1.093
4 431.8005 0.600
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328719.html
標籤:r
上一篇:categoricalToNumeric在R中運行,變數數量不定(可變函式)
下一篇:用R中的數字0交換空單元格
