You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中将数据框数值正负反转?df*(-1)方法无效求替代方案

Fixing Symbol Reversal for DataFrame Values in R

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 any NA values, they'll stay as NA (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:54:11