Reputation: 565
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. Thanks.
Upvotes: 2
Views: 7638
Reputation: 76402
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.
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
Upvotes: 4
Reputation: 23214
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
Upvotes: 2