Apple
Apple

Reputation: 13

replace values in r, preserve zeros

I want to replace all negative values to -1, positive ones with 1, and preserve the existing zeros. I have tried methods like replace, ifelse, etc. but cannot get what I want; because my existing zeros are either replaced by -1 or 1... Thanks for help!

This is a portion of my data.

1   2   2   1   0   0
1   5   8   4   3   3
1   2   1   1   0   -1
3   5   10  3   0   5
1   3   10  4   3   7
1   1   1   1   0   0
3   10  9   3   0   -1
1   4   5   1   0   1
1   1   3   1   0   2
1   2   1   1   0   -1
1   3   4   1   0   1

Upvotes: 0

Views: 69

Answers (1)

mnel
mnel

Reputation: 115390

You are looking for the function sign

sign will work on data.frames or matrices

if your data is called d

 sign(d)

Upvotes: 1

Related Questions