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?
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).
You can simply do,
change_even[c(FALSE,TRUE),] <- change_even[c(FALSE,TRUE),]*(-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With