Skip to content

How to include custom na.action in function

5 messages · Alejandro, John Fox, Jim Lemon +1 more

#
Hello,

I?ve tried googling for an answer to this but I simply can?t find something that fixes my problem. I have a long numerical vector with positive, negative and null values. I want to revert the sign of the positive and negative values and for zero to remain zero. I?ve written a function that works, except that my vector has missing values (NA) and I need to keep those as missing values. How could I add that to this function:

revertsign<-function(x){
 if (x > 0) {x <- x*-1}
   else 
if (x < 0) {x <- abs(x)}
 else
   if (x == 0) {x <- 0}
 }

I?ve tried if(is.na(x)) {x <- NA} but I get the following error message: Error in if (x > 0) { : missing value where TRUE/FALSE needed. Which I guess is the first NA in the vector which fails the first if of the function.

I use supply() to run the function on a vector.

Thanks for any assistance.

Cheers

Alejandro
#
Dear Alejandro,

If I follow what you want to do, you can just negate the vector:
[1]  10   0 -10  NA


I hope this helps,
 John

-------------------------------------
John Fox, Professor
McMaster University
Hamilton, Ontario, Canada
Web: http://socserv.mcmaster.ca/jfox/




On 2017-02-09, 2:30 PM, "R-help on behalf of Alejandro"
<r-help-bounces at r-project.org on behalf of a.gonzalezvoyer at gmail.com>
wrote:
#
Hi Alejandro,
How about:

-sign(x) * sign(x) * x

Jim
On Fri, Feb 10, 2017 at 6:30 AM, Alejandro <a.gonzalezvoyer at gmail.com> wrote:
#
Do Not do this!

?ifelse  ## (is vectorized; or use subscripting)
[1] NA  4  0  3


Please spend some time with an R tutorial or two -- there are many
good ones on the web. This is basic stuff covered in them.


Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Thu, Feb 9, 2017 at 11:30 AM, Alejandro <a.gonzalezvoyer at gmail.com> wrote:
#
Oh, after seeing John's answer, I realized I misread your x*(-1) bit
as x-1. His reply is how it should be done.

The sillier ifelse() solution is:

ifelse(x>0,-x,abs(x) )

My remark about going through a tutorial are still germane, however.

-- Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Thu, Feb 9, 2017 at 11:30 AM, Alejandro <a.gonzalezvoyer at gmail.com> wrote: