简体   繁体   English

如何将r中的数据框从正数转换为负数

[英]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.

相关问题 使用 R 对数据框和过滤结果进行连续的正或负计算 - Consecutive Positive or Negative calculation from data frame and filter results using R R:选择数据框中包含正值和负值的行 - R: select rows in data frame that contain both positive and negative values 如何对R中的数据框进行分组,使得结果表统计某列正值和负值的出现次数 - How to group the data frame in R so that resulting table counts the occurrence of positive and negative value of a column 如何将数据框中某些列的负值变为正值 - How to mutate the negative values of some columns into positive in my data frame 如何从R中的数据帧中删除负值 - how to remove the negative values from a data frame in R 如何用 R 生成随机数据以创建正或负偏斜曲线? - How to generate random data with R to create a positive or negative skewed curve? 如何将数据帧的正元素除以特定数据帧列,将负元素除以另一列? - How can I divide positive elements of a data frame by a specific data frame column and negative elements by another? 将会计数据字符串转换为整数(正数和负数) - Convert string of accounting data into integers (positive and negative) R:如何转换数据帧 - R: how to convert a data frame R - 过滤数据中的负尖峰和正尖峰 - R - filtering negative and positive spikes in data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM