3

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?

cmaher
  • 5,100
  • 1
  • 22
  • 34
Niccola Tartaglia
  • 1,537
  • 2
  • 26
  • 40

3 Answers3

10

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

library(dplyr)

df_neg <- df %>% 
  mutate_if(is.numeric, funs(. * -1))
neilfws
  • 32,751
  • 5
  • 50
  • 63
6

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
Melissa Key
  • 4,476
  • 12
  • 21
  • 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` – thelatemail May 01 '18 at 05:04
4

This is working :

data$negative = data$positive*(-1)
buddemat
  • 4,552
  • 14
  • 29
  • 49