[英]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):我想将我的 r 数据帧乘以负 1,以反转所有值的符号(将 + 转为 -,反之亦然):
This does not work:这不起作用:
df_neg <- df*(-1)
Is there another way to do this?有没有另一种方法可以做到这一点?
Here'a a tidyverse way to alter only the numeric columns.这是一种仅更改数字列的 tidyverse 方法。
library(dplyr)
df_neg <- df %>%
mutate_if(is.numeric, funs(. * -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
这是工作:
data$negative = data$positive*(-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.