s-news
[Top] [All Lists]

Re: Simple Logic If, then replacement

To: Joseph E Wolfe <Joseph_E_Wolfe@notes.ntrs.com>, s-news@wubios.wustl.edu
Subject: Re: Simple Logic If, then replacement
From: "Richard M. Heiberger" <rmh@temple.edu>
Date: Thu, 21 Apr 2005 11:15:19 -0400
>  if (test$Missing!="NA") test$Alpha<-0

if() is a logic construct used in programming.

you are attempting to use the related, but distinctly different,
logical operation on a vector: ifelse().

Also, you can't compare anything to NA with comparison operators.
They respond to the missing value with a missing result.  Instead
you need the function is.na().

If I understand what you are looking for, you need

test$Alpha <- ifelse(is.na(test$Missing), 0, test$Alpha)

ifelse() selects elementwise argument 2 or 3 depending on the value
of argument 1.

A better way to do this specific example is

test$Alpha[is.na(test$Missing)] <- 0

This variant uses logical subscripting.

Look up the help pages for
Logic
if
ifelse
is.na
Subscript

<Prev in Thread] Current Thread [Next in Thread>
  • Re: Simple Logic If, then replacement, Richard M. Heiberger <=