2

Because I'm working with a very complex table with nasty repeated values in variable places, I'd like to do a string search between specific rows and columns.

For example:

table={{"header1", "header2", "header3", 
 "header4"}, {"falsepositive", "falsepositive", "name1", 
 "falsepositive"}, {"falsepositive", "falsepositive", "name2", 
 "falsepositive"}, {"falsepositive", "falsepositive", 
 "falsepositive", "falsepositive"}}

%//TableForm=
 header1          header1          header1          header1
 falsepositive    falsepositive    name1            falsepositive
 falsepositive    falsepositive    name2            falsepositive
 falsepositive    falsepositive    falsepositive    falsepositive

How do I look for a string, for example, in column three, rows one through two?

I'd like to use Which to assign values based on a string's location in the table.

E.g.,

Which[string matched in location one, value, matched in location two, value2]
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rose
  • 129
  • 6

3 Answers3

5

As I understand it you want a test whether or not a given string is in a certain subsection of a matrix. You can pick these subsections using Part ([[...]]) and Span (;;), with which you can indicate ranges or subsamples of ranges. Testing whether or not this subsection contains your pattern can be done by MemberQ, like this:

 MemberQ[table[[1 ;; 2, 3]], "name2"]

 (* ==> False *)

 MemberQ[table[[1 ;; 2, 3]], "header3"]

(* ==> True *)

In this way, your Which statement could look like this:

myVar =
 Which[
  MemberQ[table[[1 ;; 2, 3]], "name2"], 5,
  MemberQ[table[[2 ;; 3, 4]], "falsepositive"], 6,
    ...
   True, 20
  ]
Sjoerd C. de Vries
  • 16,122
  • 3
  • 42
  • 94
2
Length[Cases[Position[table, "name1"], {1 | 2, 3}]] >= 1

Output -> True

Or

Cases[Position[table, "name1"], {1 | 2, 3}]

Output -> {{2, 3}}

681234
  • 4,214
  • 2
  • 35
  • 42
1

Perhaps, if I understand you:

f[table_, value_, rowmin_, rowmax_, colmin_, colmax_] := 
 Select[Position[table, value], 
  rowmin <= First@# <= rowmax && colmin <= Last@# <= colmax &]
f[table, "name1", 1, 10, 1, 10]
(*
-> {{2, 3}}
*)
Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190
  • I think this will work; because I'm applying it to `Which` I just need a final return of True/False on whether or not a string is within a row/column specification, but a tweak should do. Thanks so much! – Rose Aug 05 '11 at 19:04
  • @Rose I think you should un-accept my answer and accept Sjoerd's, since he understood your requirement better – Dr. belisarius Aug 06 '11 at 15:33