[英]Replace negative values with positive values in R
I am doing a task for my online course, for which I have to replace all negative values in a vector with positive in two different ways. 我正在为在线课程完成一项任务,为此,我必须以两种不同的方式用正值替换向量中的所有负值。 I have the following vector:
我有以下向量:
z <- seq(-3.5, 7, by=1.5)
The first way is with the abs()
function: 第一种方法是使用
abs()
函数:
z <- abs(z)
I am trying to think of a second way to do the same thing, maybe with a replace function or something alike. 我正在尝试另一种做同一件事的方法,也许是使用replace函数或类似的方法。 Can anyone suggest a solution?
谁能提出解决方案?
This should be fast: 这应该很快:
z<-z*sign(z)
I like akrun's answer and it is computationally fast. 我喜欢akrun的答案,而且计算速度很快。 Here is a twist on it for trivial purposes:
出于琐碎的目的,这是一个曲折:
z<--pmin(-z, z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.