Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert sign of even numbered rows in r dataframe

Tags:

dataframe

r

I have a data frame with 10 items and I want to negate the even numbered rows. I came up with this monstrosity:

change_even <- data.frame(val=runif(10))
change_even$val[row(  as.matrix(change_even[,'val']) ) %% 2 == 0 ] <- -change_even$val[row(  as.matrix(change_even[,'val']) ) %% 2 == 0 ]

is there a better way?

like image 669
Andrew Avatar asked Dec 03 '22 13:12

Andrew


2 Answers

Simply you can use recycling:

change_even$val*c(1,-1)
#[1]  0.1077468 -0.5418167  0.8319609 -0.7230043  0.6649786 -0.7232669
#[7]  0.2677659 -0.4035824  0.6880934 -0.5600653

(values are not reproducible since seed was not set; however the alternating sign can be seen clearly).

like image 103
nicola Avatar answered Dec 18 '22 04:12

nicola


You can simply do,

change_even[c(FALSE,TRUE),] <- change_even[c(FALSE,TRUE),]*(-1)
like image 26
Sotos Avatar answered Dec 18 '22 02:12

Sotos