如何在R语言中将数据框数值正负反转?df*(-1)方法无效求替代方案
Hey there! Let's break down why your df_neg <- df*(-1) might not be working, and walk through reliable ways to flip the sign of all numeric values in your dataframe.
Why the initial approach fails
Most likely, your dataframe contains non-numeric columns (like character strings, factors, or logical values). When you try to multiply the entire dataframe by -1, R can't perform this operation on non-numeric data—you might see warnings about coercion to NA, or the operation just won't affect the numeric columns as expected.
Solution 1: Base R (no extra packages needed)
Target only the numeric columns in your dataframe, flip their signs, and assign them back:
# Identify which columns are numeric numeric_columns <- sapply(df, is.numeric) # Flip the sign of numeric columns df[numeric_columns] <- df[numeric_columns] * (-1)
This way, you leave non-numeric columns untouched and only modify the values you care about.
Solution 2: Using dplyr (tidyverse workflow)
If you're using the tidyverse ecosystem, dplyr makes this super clean with across():
library(dplyr) # Create a new dataframe with flipped signs for numeric columns df_neg <- df %>% mutate(across(where(is.numeric), ~ .x * (-1)))
The across(where(is.numeric)) part tells R to apply the sign-flipping function (~ .x * (-1)) to every numeric column in the dataframe.
What if all columns are numeric but it still fails?
Double-check:
- Are your columns stored as integer or numeric? Both should work with multiplication by
-1, but if you have anyNAvalues, they'll stay asNA(which is expected behavior). - Did you accidentally run the code without assigning the result to a variable? Wait, you mentioned
df_neg <- df*(-1)—if this returns a dataframe full of NAs, that's a sure sign non-numeric columns are present.
内容的提问来源于stack exchange,提问作者Niccola Tartaglia

