[R] Sign of specific elements of a vector

Marc Schwartz marc_schwartz at me.com
Thu Jun 18 22:21:29 CEST 2015


Just to augment Bert’s comment, other options are likely to introduce some level of overhead that while perhaps looking better, will not be materially faster. Depending upon the length of your vector, you could do some testing to see.

One thing that might yield a little bit of performance improvement would be to pre-calculate the indices:

set.seed(1)
x <- rnorm(100)
IND <- seq(20,100, by=20)

> IND
[1]  20  40  60  80 100

> x[IND]
[1]  0.5939013  0.7631757 -0.1350546 -0.5895209 -0.4734006

x[IND] <- -x[IND]

> x[IND]
[1] -0.5939013 -0.7631757  0.1350546  0.5895209  0.4734006


But unless your vector is very large, I suspect the performance gain may be minimal in real time.

Regards,

Marc Schwartz


> On Jun 18, 2015, at 3:07 PM, Bert Gunter <bgunter.4567 at gmail.com> wrote:
> 
> Your **is** the "coolest" and most efficient way to do this. It's
> vectorized -- apply() stuff is not.
> 
> Cheers,
> Bert
> 
> Bert Gunter
> 
> "Data is not information. Information is not knowledge. And knowledge is
> certainly not wisdom."
>   -- Clifford Stoll
> 
> On Thu, Jun 18, 2015 at 12:40 PM, Frank S. <f_j_rod at hotmail.com> wrote:
> 
>> Hi everyone,
>> 
>> I have an "x" vector and I would want to change the sign every 20
>> elements. For this puspose,
>> I wrote the following code:
>> 
>> set.seed(1)
>> x <- rnorm(100)
>> x
>> x[seq(20,100, by=20)] <- -x[seq(20,100, by=20)]
>> x
>> 
>> However, I'm afraid  it is a rudimentary form to get the desired result.
>> II wonder wether there is a cool way to do so, that is, for example with
>> apply or sign function.
>> 
>> Thans in advanced for your help!
>> 
>> Frank S.



More information about the R-help mailing list