Niccola Tartaglia
Niccola Tartaglia

Reputation: 1667

How to convert data frame in r from positive to negative

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?

Upvotes: 3

Views: 22986

Answers (3)

Jonas Guignet
Jonas Guignet

Reputation: 41

This is working :

data$negative = data$positive*(-1)

Upvotes: 4

neilfws
neilfws

Reputation: 33782

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

library(dplyr)

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

Upvotes: 10

Melissa Key
Melissa Key

Reputation: 4551

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

Upvotes: 6

Related Questions