How to convert data frame in r from positive to negative

13,638

Solution 1

Assuming your data frame is all numeric, the code you posted should work. I'm going to assume you have some non-numeric values we need to work around

# make a fresh copy
df_neg <- df

# now only apply this to the numeric values
df_neg[sapply(df_neg, is.numeric)] <- df_neg[sapply(df_neg, is.numeric)] * -1

Solution 2

Here'a a tidyverse way to alter only the numeric columns.

library(dplyr)

df_neg <- df %>% 
  mutate_if(is.numeric, funs(. * -1))

Solution 3

This is working :

data$negative = data$positive*(-1)
Share:
13,638
Niccola Tartaglia
Author by

Niccola Tartaglia

Updated on June 05, 2022

Comments

  • Niccola Tartaglia
    Niccola Tartaglia almost 2 years

    I would like to multiply my r dataframe with minus 1, in order to reverse the signs of all values (turn + to - and vice versa):

    This does not work:

    df_neg <- df*(-1)
    

    Is there another way to do this?

    • hpesoj626
      hpesoj626 about 6 years
      What is the output of df_neg?
    • Melissa Key
      Melissa Key about 6 years
      Does your data frame have any non-numeric values? (e.g. strings or factors)
    • neilfws
      neilfws about 6 years
      That code should work (even without the parentheses). What's the error?
    • Niccola Tartaglia
      Niccola Tartaglia about 6 years
      it was indeed the non-numerics
  • thelatemail
    thelatemail about 6 years
    Looks like the right strategy to me. You can also save off sel <- sapply(df_neg, is.numeric) first so you don't have to type it all out twice. E.g.: df_neg[sel] <- df_neg[sel] * -1