问题描述
在 dplyr 工作流中,当 newvar == 0 时,我尝试在数据帧的每一列中的 newvar == 0 之后粘贴 0,否则什么都不做。 我修改了 iris 数据集:
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 across () function with mutate () and case_when () to mutate values in multiple columns according to a condition? 的解决方案。 我的理解:
- 使用
.[,3:ncol(.)]
我在 newvar 列之后浏览列。 - 使用
case_when(newvar==0
我尝试设置条件。 - 在
~ 0
之后使用newvar==0
,如果条件满足,我尝试说 paste 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 ~ .)))