簡體   English   中英

在 dplyr 問題中的 mutate 調用中使用自定義 case_when 函數

[英]Using a custom case_when function inside a mutate call in dplyr issues

我有這個數據框

library(tidyverse)
df <- structure(list(D1_step1 = c("FT", "FF", "FF", "TTT", "FFF", "FFF", 
      "FF", "FFF", "FT", "TT"), barrido = c("B1_B4", "B1_B2", "B1_B4", 
      "B1_B2_B4", "B1_B2_B4", "B1_B2_B4", "B1_B4", "B1_B2_B4", "B1_B4", 
      "B1_B4")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
      -10L))

和這個功能

f1 <- function(sero, barrido){
  as.logical(case_when(str_detect(barrido, "B1") ~ str_sub(sero, 1, 1)))
}

df %>%
mutate(new_col = f1(D1_step1, barrido))

我這樣做並且效果很好。 我不需要函數中的 barrido 參數,因為它不會改變,並且數據總是有一個名為“barrido”的列。 因此我想這樣做......

f2 <- function(sero){
  as.logical(case_when(str_detect(barrido, "B1") ~ str_sub(sero, 1, 1)))
}

df %>%
mutate(new_col = f2(D1_step1))

 Error in stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) : 
  object 'barrido' not found

但是計算機說不,所以我嘗試將參數設置為默認值,但我得到了另一種不。 Nb 剛剛編輯了這個,因為我實際上並沒有將參數設置為默認值

f3 <- function(sero, barrido = barrido){
  as.logical(case_when(str_detect(barrido, "B1") ~ str_sub(sero, 1, 1)))
}

df %>%
mutate(new_col = f3(D1_step1))

 Error in stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) : 
  promise already under evaluation: recursive default argument reference or earlier problems?

使用 tidyeval 編寫自定義 case_when 函數以在 dplyr mutate 中使用 這個問題沒有幫助,因為我不想在 mutate 中將函數編寫為 case_when。 下面的評論說明了為什么這不起作用,並讓我相信可能有使用 tidyeval 的解決方案。 我也很好奇 f2 和 f3 之間的錯誤消息之間的差異背后是什么。

隨着dplyr的開發版本(被釋放dplyr 1.0),你可以在當前列有偷看across()

f2 <- function(sero){
  barrido <- across(all_of("barrido"))[[1]]
  as.logical(case_when(
    str_detect(barrido, "B1") ~ str_sub(sero, 1, 1)
  ))
}

應該清楚地記錄此功能僅在 dplyr 內部使用包含barrido列的數據框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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