Message Boards Message Boards

0
|
4395 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Rule based command on lists

Posted 9 years ago

Hello group,

I'm trying to translate a program written in the R language into Mathematica. R is a statistical language and is similar to Mathematica in many respects. There is one command called ifelse(test, result if true, result if false) that operates on two lists. What it does in this instance is to generate a list A from the two lists ca and p: A=ifelse(abs(ca) > p, sign(ca),0) The resulting list A contains the sign of a value in the list ca if the absolute value of the element ca is greater than the corresponding value of the element in list p (p is all positive values), and 0 otherwise. I haven't been able to do this in Mathematica without going to a Do procedural command. Is there a rule based command for doing this? John Reed

POSTED BY: John Reed
2 Replies
Posted 9 years ago

del

POSTED BY: Bill Simpson
Posted 9 years ago

Study the help pages for these functions until you think you understand it

And test it carefully before you depend on it.

Method 1:

In[1]:= ca = {-5, 2, 1, -4};
p = {4, 3, 0, 2};
f[{ca_, p_}] := If[Abs[ca] > p, Sign[ca], 0];
Map[f, Transpose[{ca, p}]]

Out[4]= {-1, 0, 1, -1}

Method 2. Perhaps more cryptic, but more in the usual Mathematica programming style.

In[5]:= ca = {-5, 2, 1, -4};
p = {4, 3, 0, 2}; Map[
 If[Abs[#[[1]]] > #[[2]], Sign[#[[1]]], 0] &, Transpose[{ca, p}]]

Out[6]= {-1, 0, 1, -1}
POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract