Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Type mismatch error when comparing a string variable across rows

    Hello, I am facing trouble in Stata 14.2 when comparing a string variable across rows (i.e., observations). Consider the following toy data:

    Code:
    clear all
    set obs 3
    gen string_var = "a"
    gen numeric_var = 1
    If I compare the values of the variables across the three observations, I face no problem for the numeric variable but get an error for the string variable. I run (and get):

    Code:
    count if numeric_var == numeric_var[_n+1] == numeric_var[_n+2]
     1
    
    count if string_var == string_var[_n+1] == string_var[_n+2]
    type mismatch
    r(109);
    Why am I getting the type mismatch error for the string variable?

  • #2
    The problem arises because evaluations of the form

    Code:
    a == b == c
    are resolved in this way. First a == b is evaluated, as 1 if true or 0 if false; either way the result is numeric and so if c is string, the result is a type mismatch.

    Code:
     
     count if (string_var == string_var[_n+1]) &  (string_var[_n+1] == string_var[_n+2]_

    Comment


    • #3
      Ah, so my numeric variable spuriously gave me the correct result. Thanks very much, Nick!

      Comment

      Working...
      X