簡體   English   中英

結合 mutate(across) 和 case_when 根據條件用 0 填充多列

[英]combine mutate(across) and case_when to fill multiple columns with 0 depending on condition

在 dplyr 工作流程中,當 newvar == 0 時,我嘗試在 dataframe 的每一列中粘貼一個 0 到 newvar 列之后,否則什么也不做。 我修改了虹膜數據集:

library(dplyr)
n <- 150 # sample size

iris1 <- iris %>% 
    mutate(id = row_number(), .before = Sepal.Length) %>% 
    mutate(newvar = sample(c(0,1), replace=TRUE, size=n), .before = Sepal.Length ) %>% 
    mutate(across(.[,3:ncol(.)], ~ case_when(newvar==0 ~ 0)))

我嘗試了像這里這樣的解決方案How to combine the cross () function with mutate () 和 case_when () 根據條件改變多列中的值? . 我的理解:

  1. 使用.[,3:ncol(.)] I go 通過 newvar 列之后的列。
  2. 使用case_when(newvar==0我嘗試設置條件。
  3. newvar==0 0 之后使用~ 0如果條件滿足,我會嘗試說粘貼 0。

我知道我做錯了什么,但我不知道是什么。 謝謝您的幫助。

.[,3:ncol(.)]是列的值,而不是實際的列號。 使用3:ncol(.)應該可以正常工作。

通常,最好避免按位置引用列,而是使用它們的名稱。 您可以在一個mutate調用中執行此操作。

library(dplyr)

n <- 150

iris %>% 
  mutate(id = row_number(), 
        newvar = sample(c(0,1), replace=TRUE, size=n), 
        across(Sepal.Length:Petal.Width, ~ case_when(newvar==0 ~ 0, 
                                                     newvar == 1 ~ .)))

暫無
暫無

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

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