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)
Author by
Niccola Tartaglia
Updated on June 05, 2022Comments
-
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 about 6 yearsWhat is the output of
df_neg
? -
Melissa Key about 6 yearsDoes your data frame have any non-numeric values? (e.g. strings or factors)
-
neilfws about 6 yearsThat code should work (even without the parentheses). What's the error?
-
Niccola Tartaglia about 6 yearsit was indeed the non-numerics
-
-
thelatemail about 6 yearsLooks 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