[英]How to make progressive operations in data frames with dplyr or similar R packages?
我有這個數據框:
df <- data.frame(a = c(1,2,3,4,5),
b = c(6,5,4,6,1))
我需要創建一個“ c”列,將“ a”中的第i個元素與“ b”中的第(i + 1)個元素相加並將其存儲在“ c”的第i個位置, 'c'的最后一個元素將等於其相應的'a'值的值。 在for循環中,代碼如下所示:
#Initialize the 'c' column
df$c <- vector("double", nrow(df))
#For Loop
for(i in (1:(nrow(df)-1)){
df$c[i] <- df$a[i] + df$b[i+1]
}
df$c[nrow(df)] <- df$a[nrow(df)]
我對dplyr :: mutate()很熟悉,但是我不知道如何用該函數替換該循環。 dplyr或其他軟件包中是否還有其他功能可以幫助我完成此類操作?
在dplyr
使用lead()
:
df %>%
mutate(c = a + lead(b, default = 0))
您可以使用data.table::shift
來將b列加到a:
dt[, C := ifelse(is.na(shift(b, type="lead")), a, a + shift(b, type="lead"))][]
或使用replace
處理尾箱:
dt[, C := {
x <- shift(b, type="lead")
a + replace(x, is.na(x), 0)
}]
錯過了shift
的fill
參數(即dplyr::lead
的default
)
df[, C := a + shift(b, fill=0, type="lead")]
數據:
library(data.table)
dt <- data.table(a = c(1,2,3,4,5),
b = c(6,5,4,6,1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.