簡體   English   中英

如何使用dplyr或類似的R包對數據幀進行漸進操作?

[英]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)
    }]

錯過了shiftfill參數(即dplyr::leaddefault

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM