![](/img/trans.png)
[英]Convert a data frame with integer columns to a list column, where each element in the list is an integer vector
[英]Perform arithmetic on each element of a vector (column) based on the previous vector element over multiple vectors (columns) in a data frame
我有一個包含12列的數據框,我需要對其中的7列執行一些基本的算術運算:列5:12。 名為test的數據框粘貼在下面。
我要執行的算術運算將基於除每個列中的第一個元素以外的上一個元素來更改每個元素,因為每列的第一個元素的算法與后續元素不同。 而且,元素向量將因涉及原始值而由方程式更改。 我對上一行代碼中的第一個元素進行了算術運算,因此這已經是正確的值。
這是數學公式:
B = (1-.08)Bt + .08(z)
其中Bt是前一個元素的值,z是當前元素的值。 每個元素將變為B。
編輯:我可能還不清楚,但是Bt將是前一個元素的B的新計算值。 因此,這是逐步進行的。
我一直在嘗試應用apply,但是我感到困惑,因為過去我只使用for循環對單個向量執行了類似的操作,但是在這種情況下,我基於先前的元素創建了全新的向量元素,並且像本例一樣,第一個元素是預定義的。
我可以概念化它,但是不能用我目前在R中使用的技能進行編碼。
任何幫助深表感謝。 謝謝。
數據:
test <-
structure(list(Forecast_day = c(8, 8, 8, 8, 8, 8), Forecast_date = structure(c(17555,
17556, 17557, 17558, 17559, 17560), class = "Date"), DeliveryDate = structure(c(17563,
17564, 17565, 17566, 17567, 17568), class = "Date"), HourEnding = c(1L,
1L, 1L, 1L, 1L, 1L), Coast = c(-0.0459999999999999, -11.6, -3.8,
-7.09999999999999, -9.6, -11.2), East = c(0.01, -8.5, -1.5, -3.5,
-0.5, -9.5), FarWest = c(-0.07, -6.5, -9, -11.5, 6, -10.5), North = c(0.01,
-2.5, -1.5, -1.5, 14, 0), NorthCentral = c(-0.07, -7.25, -5.75,
-10.75, 6.75, 1.5), SouthCentral = c(-0.01, -10, -8.5, -3.5,
-8.5, -11), Southern = c(-0.04, -10.8, -4.6, -7.8, -9.6, -12),
West = c(-0.16, -7.4, -6.6, -13.2, 7.8, -9)), .Names = c("Forecast_day",
"Forecast_date", "DeliveryDate", "HourEnding", "Coast", "East",
"FarWest", "North", "NorthCentral", "SouthCentral", "Southern",
"West"), row.names = c(NA, -6L), class = "data.frame")
您可以使用Reduce
元函數,將先前的結果用作輸入之一,從而沿向量順序應用算術。
首先,將算術包裝在一個函數中。
update_with_previous <- function(previous, current) {
(1 - 0.08) * previous + 0.08 * current
}
要在一列中執行此操作,請使用Reduce
的函數並設置accumulate = TRUE
以保留每個結果。
Reduce(update_with_previous, test$Coast, accumulate = TRUE)
# [1] -0.046000 -0.970320 -1.196694 -1.668959 -2.303442 -3.015167
使用lapply
替換多個列。
test[5:12] <- lapply(
X = test[5:12],
FUN = Reduce,
f = update_with_previous,
accumulate = TRUE
)
可能有一些更優雅的方法,但是我認為這會起作用:
B <- function(Bt,z) (1-.08)*Bt + .08*(z)
tmp <- sapply(test[,5:12] ,function(g) sapply(2:nrow(test),function(x) B(Bt = g[x-1],z = g[x])))
test[2:nrow(test),5:12] <- tmp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.