求tidyr中更简洁的管道式按列条件更新列值语法
使用tidyr实现更简洁的条件赋值为NA
直接给出满足需求的tidyr简洁写法:
library(tidyr) iris_df <- iris %>% replace_with_na(replace = list(Sepal.Length = ~Species == "setosa"))
说明
replace_with_na是tidyr专为条件替换为NA设计的函数,语法上通过list(目标列 = ~条件表达式)指定规则,无需重复引用目标列(对比dplyr的mutate写法需要两次写Sepal.Length),代码更紧凑,同时完美适配管道流。
各写法对比
- Base R(合并单行写法):
iris_df <- transform(iris, Sepal.Length = replace(Sepal.Length, Species == "setosa", NA)) - dplyr写法:
iris_df <- iris %>% mutate(Sepal.Length = if_else(Species == "setosa", NA_real_, Sepal.Length)) - tidyr写法(更短):
iris_df <- iris %>% replace_with_na(replace = list(Sepal.Length = ~Species == "setosa"))
如果需要批量处理多列,replace_with_na的优势更突出,比如同时将setosa对应的多个特征设为NA:
iris_df <- iris %>% replace_with_na(replace = list( Sepal.Length = ~Species == "setosa", Petal.Length = ~Species == "setosa" ))
内容的提问来源于stack exchange,提问作者moreQthanA
相关产品推荐
相关产品推荐

