关于dplyr中mutate函数的疑问及mutate_each()弃用报错问题
Hey there! Let's tackle this dplyr mutate issue you're facing—those deprecation warnings can be annoying at first, but the replacement functions are actually more flexible once you get the hang of them.
First, let's confirm: mutate_each() was indeed retired in newer dplyr versions, and the recommended replacements are mutate_all(), mutate_at(), and mutate_if()—each tailored for different scenarios, especially handy for your binary (0/1) dataframe.
Let's break down each function with binary data examples:
mutate_all(): Apply a function to every column in your dataframe
If all your columns are binary and you want to flip every value (0 ↔ 1), you can do:library(dplyr) # Flip all binary values df <- df %>% mutate_all(~ 1 - .)mutate_at(): Target specific columns (the most common choice for selective changes)
This is perfect when you only want to modify certain columns (e.g., columns with "flag" in the name, or specific column indices). For example:# Flip values in columns named flag1, flag2, flag3 df <- df %>% mutate_at(vars(flag1, flag2, flag3), ~ 1 - .) # Or use dplyr's column selectors for broader matches df <- df %>% mutate_at(vars(starts_with("flag")), ~ 1 - .)Pro tip: You can also create new columns directly by adding a suffix/prefix with
list():# Create flipped versions of flag columns with "_rev" suffix df <- df %>% mutate_at(vars(starts_with("flag")), list(rev = ~ 1 - .))mutate_if(): Apply a function to columns that meet a condition
If your binary columns are of a specific type (e.g., integer or logical), you can target them dynamically:# Flip all integer-type binary columns df <- df %>% mutate_if(is.integer, ~ 1 - .) # If your binary data is stored as logical (TRUE/FALSE), convert to 0/1 and flip df <- df %>% mutate_if(is.logical, ~ as.integer(!.))
Common pitfalls to check if you're still having issues:
- Outdated dplyr version: Make sure you're running the latest version—older versions might have syntax differences (like requiring
funs()instead of the~shorthand). - Incorrect column type: If your binary data is stored as characters ("0"/"1"), you'll need to convert to numeric first:
df <- df %>% mutate_if(is.character, ~ 1 - as.integer(.)) - Missing
vars()wrapper: When usingmutate_at(), always wrap your column selections invars()—forgetting this will throw an error.
Here's a full working example to tie it all together:
# Sample binary dataframe df <- tibble( id = 1:5, flag1 = c(0,1,0,1,0), flag2 = c(1,1,0,0,1), flag3 = c(0,0,1,1,0) ) # Create reversed flag columns df_updated <- df %>% mutate_at(vars(starts_with("flag")), list(rev = ~ 1 - .))
内容的提问来源于stack exchange,提问作者user7512829

