[英]Trying to perform a case_when function inside a mutate verb in R
[英]Trying using lag function inside case_when in a cumulative operation in R. Loop necessary?
我正在嘗試創建一個新列,結合 dplyr 中的 mutate() 和 case_when() 函數。從代碼為“start”的字符串開始,我需要在代碼為“fi”時減去另一個字符串,或者在代碼為“fi”時添加一個字符串“福”,累加運算。 當代碼為“fi”或“fu”時,前一次應用 function 的結果應用作下一次的參數。 我嘗試使用 lag() 以便在上述結果中減去/添加一個字符串。 我認為我得到的錯誤是因為新列還不是我可以在 case_when() function 中引用的 object。
library(tidyverse)
df <- tibble(code = c("start","fi","fu","fi","start","fi","start","fu"),
id = c("x,y,", "y,", "z,p,", "p,", "z,p,", "p,", "x,y,z,", "p,q,"))
# A tibble: 8 × 2
code id
<chr> <chr>
1 start x,y
2 fi y,
3 fu z,p,
4 fi p,
5 start z,p,
6 fi p,
7 start x,y,z,
8 fu p,q,
# the desired output is
code id id2
<chr> <chr> <chr>
1 start x,y x,y,
2 fi y, x,
3 fu z,p, x,z,p,
4 fi p, x,z,
5 start z,p, z,p,
6 fi p, z,
7 start x,z, x,z,
8 fu p,q, x,z,p,q,
# I tried this
df %>% mutate(id2 = case_when(code == "start" ~ id,
code == "fu" ~ paste0(lag(id2,1), id),
code == "fi" ~ str_replace_all(lag(id2,1), id, "")
Error in `mutate()`:
! Problem while computing `id2 = case_when(...)`.
Caused by error in `lag()`:
! object 'id2' not found
Run `rlang::last_error()` to see where the error occurred.
您可以使用purrr::accumulate2()
執行此操作。 accumulate()
沿向量應用 function,每個“步驟”的結果可用作下一個“步驟”的輸入。 accumulate2()
的作用相同,但有兩個輸入向量(例如,您的code
和id
列)。
library(dplyr)
library(purrr)
library(stringr)
df %>%
mutate(id2 = unlist(accumulate2(
id,
code[-1],
\(id2, id, code) case_when(
code == "start" ~ id,
code == "fu" ~ paste0(id2, id),
code == "fi" ~ str_remove_all(id2, id)
)
)))
# A tibble: 8 × 3
code id id2
<chr> <chr> <chr>
1 start x,y, x,y,
2 fi y, x,
3 fu z,p, x,z,p,
4 fi p, x,z,
5 start z,p, z,p,
6 fi p, z,
7 start x,y,z, x,y,z,
8 fu p,q, x,y,z,p,q,
您需要使用unlist()
(或as.character()
),因為accumulate2()
返回一個列表。 你需要傳遞code[-1]
而不僅僅是code
因為accumulate2()
期望第二個向量比第一個向量短。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.