Skip to content

Multiple logical operations in a subscript

4 messages · Mark, Peter Alspach, Greg Snow +1 more

#
Hello,

I would like to select cases using multiple logical operations (e.g. X 
or Y or Z) without having to repeat the dataframe$variable within the 
subscript. My working code (with a single logical operator) currently 
looks like this:

dataframe$newvariable[data$oldvariable=="X"]<-"group1"

I thought this next line of code might do what I wanted, but it doesn't:

dataframe$newvariable[data$oldvariable=="X" | "Y" | "Z"]<-"group1"

I'd appreciate any suggestions. I've tried playing around with grep, but 
can't make it work.

Thanks! Mark
#
Mark

Try

dataframe$newvariable[data$oldvariable %in% c("X","Y","Z")] <- "group1" 

HTH ...

Peter Alspach
The contents of this e-mail are privileged and/or confidential to the named
 recipient and are not to be used by any other person and/or organisation.
 If you have received this e-mail in error, please notify the sender and delete
 all material pertaining to this e-mail.
#
Peter showed you the %in% operator, you may also want to look at the subset, transform, with, and within functions for future use as ways to reduce the need to type the name of an object multiple times.

Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111
#
On 19-Sep-08 16:03:45, Greg Snow wrote:
Let me add my perhaps very simple-minded suggestion. What I usually
do in such a situation is to define a working variable with a short name.
So, in the case of your example:

  dataframe$newvariable[data$oldvariable=="X" | "Y" | "Z"]<-"group1"

I would:

  Old<-data$oldvariable
  dataframe$newvariable[(Old=="X")|(Old=="Y")|(Old=="Z")] <- "group1"

which is what I take your intended meaning to be -- if so, then your
formulation of the condition is wrong, since

  data$oldvariable=="X" | "Y" | "Z"

will first (because of precedence rules -- see ?Syntax) evaluate
  data$oldvariable=="X""
(to TRUE or FALSE), and then try to OR ("|") this with the values
of "X and "Z". Since these are character strings, the operation is
not permitted:

  "Y"|"Z"
  Error in "Y" | "Z" : 
    operations are possible only for numeric or logical types

On the other hand:

  1|(-2)|(3.14159)
  [1] TRUE

Hoping this helps,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 19-Sep-08                                       Time: 17:28:20
------------------------------ XFMail ------------------------------