[英]Assign a negative sign to every value in a vector (in R)?
I want this: 我要这个:
V <- c(2, 3, 4, 5, 6)
V <- as.data.frame(V)
To look like this: 看起来像这样:
[1] -2 -3 -4 -5 -6
Essentially the reverse of the abs() function. 基本上与abs()函数相反。 Thanks. 谢谢。
I believe that if you don't know beforehand whether all values of the vector are positive, then you should do something like the code below. 我相信如果您事先不知道矢量的所有值是否为正,那么您应该执行类似下面的代码。
V <- c(2, 3, 4, 5, 6)
W <- c(-2, -3, -4, -5, -6)
X <- c(2, -3, 4, -5, 6)
all.neg <- function(x) -1*abs(x)
Let's try it. 我们来试试吧。
all.neg(V)
#[1] -2 -3 -4 -5 -6
all.neg(W)
#[1] -2 -3 -4 -5 -6
all.neg(X)
#[1] -2 -3 -4 -5 -6
If you want to apply it to a data.frame, then do it the usual way. 如果要将其应用于data.frame,请按常规方式执行。
dat <- data.frame(V, W, X)
dat[] <- lapply(dat, all.neg)
dat
# V W X
#1 -2 -2 -2
#2 -3 -3 -3
#3 -4 -4 -4
#4 -5 -5 -5
#5 -6 -6 -6
You could do 你可以做到
V * -1
or 要么
-V # first mentioned in the comments by @RHertel
or anything like that. 或类似的东西。 With assignment (updating the object) it looks like this: 通过赋值(更新对象),它看起来像这样:
v <- v * -1 # or -V
You can also use =
for assignment but it goes against the style guides. 您也可以使用=
进行分配,但它违反了样式指南。
[1] -2 -3 -4 -5 -6 [1] -2 -3 -4 -5 -6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.