if-statement,stata , Mutually exclusive conditionals don't work in Stata

Mutually exclusive conditionals don't work in Stata


Tag: if-statement,stata

I have some data on Stata with some variables like logTA and class. I have more than a thousand observations and logTA doesn't have any missing values. Data looks like this:

logTA       class
--------    --------

Now, what I want to do is to assign values to class variable according to the following simple rules:

replace class = 1 if logTA < mean(logTA) - sd(logTA)
replace class = 2 if logTA >= mean(logTA) - sd(logTA) & logTA < mean(logTA) + sd(logTA)
replace class = 3 if logTA >= mean(logTA) + sd(logTA)

It looks simple but Stata doesn't have mean() and sd() functions that can be used in this way. Anyway, I replaced mean(logTA) with 19.76543 and sd(logTA) with 1.507828.

However, among many a thousand of observations, the observation with logTA = 21.26871 isn't assigned any class. How this could be possible when my conditionals are mutually exclusive?

Here I uploaded my file: http://wikisend.com/download/187254/problem.dta When I was trying to simplify the data set to send here, I realized that changing variable names solves the problem. So, in order to reproduce the error, just run the following code and check the last 9 rows.

gen sBuyuklukSinifi = .
replace sBuyuklukSinifi = 1 if logmToplamVarliklar < 19.76543 - 1.507828
replace sBuyuklukSinifi = 2 if logmToplamVarliklar >= 19.76543 - 1.507828 & logmToplamVarliklar < 19.74152 + 1.507828
replace sBuyuklukSinifi = 3 if logmToplamVarliklar >= 19.76543 + 1.507828


Here's how I might accomplish this:

/* Fake Data */
set seed 5615
set obs 100000
generate logTA = rnormal(19.76543,1.507828)
replace logTA=21.26871 in 1

summarize logTA, detail
generate class = . 
replace class = 1 if logTA < r(mean) - r(sd)
replace class = 2 if inrange(logTA,r(mean) - r(sd),r(mean) + r(sd))
replace class = 3 if logTA >= r(mean) + r(sd)

Results of calculations are stored by summarize in r() so that they can be easily accessed and substituted into subsequent commands, instead of typing the values.

I am not sure why your code does not work. I get the same answer as above with:

generate class2 = . 
replace class2 = 1 if logTA < 19.76503 - 1.513932
replace class2 = 2 if inrange(logTA,19.76503 - 1.513932,19.76503 + 1.513932)
replace class2 = 3 if logTA >= 19.76503 + 1.513932
tab class class2


R: recursive function to give groups of consecutive numbers

Given a sorted vector x: x <- c(1,2,4,6,7,10,11,12,15) I am trying to write a small function that will yield a similar sized vector y giving the last consecutive integer in order to group consecutive numbers. In my case it is (defining groups 2, 4, 7, 12 and 15): > y...

Convert a string to a double for a if clause

I'm trying to convert a string to a double, so I can use the double to compare it with another one, to make the result green if it's the same or red when not. The first method is: public void getCords(View view) { double latitude; double longitude; latitude = 1.00;...

How do I format the logic for 3 conditions and use a previous condition as well?

NOT ASKING FOR ANYONE TO WRITE THE PROGRAM FOR ME I am having trouble understanding how to setup the logic for a program given these following conditions: For every day late up to and including 7 days, the late fee is $0.10/day After 7 days, for every day late up...

SQL Syntax error #1064 cursors (mysql)?

So my procedure looks something like this: OPEN tstamp_cursor; get_timestamp: LOOP FETCH tstamp_cursor INTO cSID, ctstamp; IF finished = 1 THEN LEAVE get_timestamp ; END IF; SET @MID = 0; SET @MX = 0; SET @MY = 0; SET @MT = 0; SELECT @MID:=m.vID, @MX:=m.x , @MY:=m.y , @MT:=m.timestamp FROM...

python if statement inside for syntax error

I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement: #search for 9 elements file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w') for item in data_indices: flag= search_object(item,data,obj_value_min,obj_value_max) if flag = True:###ERROR file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax...

Rails keeps ignoring an IF statement inside the view

I am writing an application where I want to list blog posts according to date they were created on the main index page. So lets say if I have 10 blog posts that were created today I would want to have smth like this come on the index page of...

How to make nested IF statements neater

This question could be asked in a language independent way but I'm asking in the context of python since different languages will have different nuances. I recognize that this is similar to this question but I think mine is different in that I'm asking about a case where putting the...

The program after if statement is not exectuing

I have a problem with escaping from if, my code looks more or less like this in python: if answear == "Yes": do something pylab.show() if anwear == "No": do something pylab.show() answear2= input("How are you?") print ("I'm here") The problem is that is statement works nicely but after showing...

Comparing cell contents against string in Excel

Following is my table file:*.css file:*.csS file:*.PDF file:*.PDF file:*.ppt file:*.xls file:*.xls file:*.doc file:*.doc file:*.CFM file:*.dot file:*.cfc file:*.CFM file:*.CFC file:*.cfc file:*.DOC I need a formula to populate the H column with True or False if it finds column G in column F (exact case). I used following but nothing seems to...

Time's Tables Quiz (Error)

HELP NEEDED :D So trying to embark on making a time's tables quiz for my brother.Very new to coding so trying to do it as simple as possible but really stuck. Any help would be awesome Basically I keep getting this error [ In function 'main': Line 17: error: expected...

Display only values containing specific word in array

Right now I am working on a search function for my json decoded results. The code that I got looks like this: <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $val["Text"]; echo '<tr><td>' . $value . '</td><td>' . $seotitle . '</td><td>' . $text ....

How do I check whether a file or file directory exist in bash?

I currently have this bash script (which is located in my home directory, i.e., /home/fusion809/ and I am running it as root as it's necessary for the icon copying lines): cd /home/fusion809/Pictures/Icon* declare -a A={Arch,Debian,Fedora,Mageia,Manjaro,OpenSUSE} declare -a B={Adwaita,Faenza,gnome,Humanity} for i in $A; do for j in $B; do if test...

Java dice roll with unexpected random number

I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 [email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Jquery, Javascript click && value

how do I check inside jquery if a button is clicked and if the variable test has an integer of 1? I have done this so far. $(".bx-next").click(function() && (test == 1){ $("#step_1").text("Hello world!"); }); ...

using if statements in tableau on a contains function

Say I have city populations for each state / city in the united states. I want to mark each city with over 2 million population as a big city. then if a state contains a "big city", i want to mark that state as a "big state". I made a...

PostgreSQL conditional statement

I need to implement a conditional SELECT statement based on the result of another statement. I don't want to create a function for this purpose, but simply using conditional SELECT. My unsuccessful approach looks as below: DO $do$ BEGIN IF SELECT count(*) FROM table1 < 1 THEN SELECT * FROM...

How do I get my logic in this Java program to make my loop work?

I've made this java program to find the two smallest integers as inputted by the user. I think I'm pretty much just about there except there is one issue with my logic. I'm not sure what to set values: int min, min2; to where the rest of my program would...

Python AND OR statements

I am parsing text with Python and I have this final code to write sentences, but it does not work well: opt = child.get('desc') extent = child.get('extent') if opt == 'es': opt = "ESP:" elif opt == "la": opt = "LAT:" elif opt == "en": opt = "ENG:" if opt...

Export average value of one variable over 2 other variables

I can use tabout var1 var2...style(csv) to export a matrix-like object with var1 on one axis, var2 on the other, and the frequencies that each combination of the values var1 and var2 occur. Is it possible to use tabout or some other commmand (preferably native to Stata) to do something...

SAS else if clause confusion

I'm running the following code: data new; set old; if visits=. then band='Poor'; else if visits=1 or visits=2 then band='Low'; else band='High'; run; My confusion is when the else if statement is changed to: else if visits=1 or 2 then band='Low'; Why does the value Low appear as the band...

Replace the following query in sqlite

I have a sql server query as follows in a store procedure with parameters @firstId and @secondId IF @firstId = '' begin SELECT DISTINCT x, y = FROM t1 LEFT OUTER JOIN t2 ON t1.id = t2.id AND t2.id = @secondId ORDER BY t1.somecolumn END ELSE BEGIN SELECT DISTINCT x,...

Hiding #DIV/0! Errors Using IF and COUNTIF in Excel 2010

I'm working on a tracking sheet for quality reviews of work completed. I have a list of criteria to be met for which the entry can be either Y or N, or X for not applicable. Each month a number of these reviews will be done on each person. In...

Stop Prevent Default in else clause

Hello I have a mobile nav where some items have a subnav so I have set a preventDefault to stop these doing there normal actions and open the sub menu but some don't have a submenu ad now these don't work as normal. Any help would be great here is...

Stopping condition on a recursive function - Haskell

So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

using if else with codeigniter return value

I am using codeigniter framework for one of my inventory management systems. I prefer using php due to its variable functionality which makes things easier. So I am trying to get the username from session and then check the database for the level of the user and accordingly he should...

Chance of a conditional occurring in Swift: Xcode

I am quite new to Xcode and swift so sorry if this is a bad description. Is there a way that there is a chance of your conditional occurring so instead of it happening 100% of the time when the conditions are met, it only happens 50% of the time...

Align bars in ciplot

I'm working with the ciplot graphing module for Stata and am encountering a problem with the alignment of bars when I use the by() option. Here's a trivial example demonstrating the issue: webuse citytemp, clear ciplot heatdd cooldd, by(region) horizontal recast(conn) So, the graph shows means and confidence intervals for...

The if statement doesn't work for false in php

When trying to get familiar with if statement in PHP, this happened. First time i tried this code below. if(true) {echo 'true';} else {echo 'false';} And the output was true when the condition is true. Again, when the condition is false (if(false)) it echos false. But i tried the same,...

Python - Using a created list as a parameter

When I run my code it tells me: Type Error: unorderable types: str() < float(). I can't figure out why it won't let me compare these two numbers. The list I am using is defined, and the numbers in it have been redefined as floats, so I'm not sure what...

second else if stament is NOT working properly

My second "else if" is not working. I cannot download the file if the file is not there. I do not know what I'm doing wrong here. #!/bin/bash # upper case file_upper_case=/root/MASTER.txt # lower case file_lower_case=/root/master.txt if [ -e "$file_upper_case" ]; then echo "File is upper-case" echo "Changed to lower_case"...

jQuery - clearInterval seems not to work

Long story short: If the interval count exceeds 5 the code should clear the interval, stopping it from executing the function every second. But this doesn't seem to work. HTML <div id='feedback'></div> JavaScript / jQuery window.intervalcount = 0; var interval = setInterval(function () { intervalcount += 1; $("#feedback").text(intervalcount); }, 1000);...

Translating Stata to R: collapse

Just came across a .do file that I need to translate into R because I don't have a Stata license; my Stata is rusty, so can someone confirm that the code is doing what I think it is? Here's the Stata code: collapse (min) MinPctCollected = PctCollected /// (mean) AvgPctCollected...

If and only if in vb.net 4?

IIF seems to be unavailable in .net 4, do we have a replacement? IIf(condition = 0, True, False) Would be a simple if statement a good replacement?...

What is the best way to rewrite this repeated if statement?

I'm thinking there is an easier way to write this code, but not sure on what approach to take. Basically, I want to check if each variable exists, and if so - add the appropriate markup to the page. Any suggestions would be great. <?php $words = get_field('words'); $photography =...

Combining multiple for loops into one using the OR operator

This is probably a simple question, but I can't get it to work. I've searched and have tried all the suggestions people gave for the OR operator ||, but my code just won't properly use it. So here's what I've got: This part of my code looks at a vector...

Have an if statement look ONLY at the first word in a string [duplicate]

This question already has an answer here: how to check string start in C++ 9 answers I have a vector composed of strings, some strings have single words, some have multiple words, some have numbers, etc. I have a code that deletes elements of the vector IF the entire...

If statement for search field in Rails

I have a blog site and recently added a search bar for visitors to browse through blog posts. When used, all of the posts go away in the directory and only those which return via the search appear. In order to show the general directory and view all, I would...

Python Reuse a Variable in the Else Block of an If-Else Statement

I'm currently working on a simple file transfer program in Python. I am having trouble with the function for prompting the user for the location of the folder to be copied. def getSrc(): if getSrc.has_been_called is False: source = askdirectory() getSrc.has_been_called = True return source else: return source getSrc.has_been_called =...

Swift won't allow me to use `!=`

Currently trying to check if three values, that I just converted from Strings to doubles, are nil from the UITextFields aValue, bValue, and cValue. I don't get a compile error from these variables until the if statement at the bottom of the code block (shown below) where it causes a...

How does this code print odd and even?

#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

[: : integer expression expected

COUNTER=0 let COUNTER=COUNTER+1 count=`ssh -i /var/www/.ssh/id_rsa_root -o stricthostkeychecking=no $host $cmd` count1=`echo $count | awk '{print $4}'` printf "count1 : $count1\n" result1=${count1/.*} if [ "$result1" -ge "0" ]; then echo $host else echo $host exit fi If the value of $result1 is INTEGER and greater than zero, it'll goto IF loop...

Excel IF AND OR condition together

I am trying to use this formula in excel but am getting an error. Can someone please help? =IF(OR(AND(B2>=Sheet3!$B$4,B2<=Sheet3!$C$4),AND(B2>=Sheet3!B6,B2<=Sheet3!C6))),"Blue","Grey") Programmatically, I am trying to get this: If((a>x && a<y) || (a>x1 && a<y1)){ Blue } else { Grey } ...

How to make if statement that checks if multple listBoxes are empty or not?

How do I make an if statement that asks if multiple listBoxes are empty or not? This is what I have so far...is it possible to combine it into one single if statement? if (listBoxEmails.Items.Count < 1) { //Perform action } if (listBoxWebsites.Items.Count < 1) { //Perform action } if...

If/else problems in python

Ok, I'm gonna explain this as best I can. I am trying to make an if/else statement in python that basically informs the user if they put in the right age based on raw input, but I keep getting an error in terms of my if statement. Can I get...

My batch files if else statement isn't working

So I have created a file that works and when testing it without the if/else statement. When I put in this in a if statement it doesn't work at all though, is my syntax wrong or what? Thanks. @echo off set /p id= Folder Name: set /p yn= Subfolders? (y/n):...

Get actual path from path with wildcard

When using Test-Path in an if statement, I am looking to get the path that the if statement succeeds with. For example, these files exist in C: C:\Test6_1_15.txt C:\Test6_2_15.txt C:\Test6_3_15.txt C:\Test6_4_15.txt what do I do in the "then" branch? $Path = "C:\Test6_*_15.txt" if (Test-Path $Path) { # if test passes...

if condition in try process

i have some problem when trying to implement condition in "try" process, the result always of "globalnidn" always isi , therefore i've checked in logcat and the result is fine. :( protected void onPostExecute(String data) { try { JSONObject jObject = new JSONObject(data); globalnidn = null; globalnidn = jObject.getString("nidn"); String...

Check if VB.net dataset table exists

I have the following code to check if my table exists before proceeding If ds.Tables(3).Rows.Count = 0 Then MsgBox("Nothing!!!!") Else DataGridView1.DataSource = ds.Tables(3) The trouble is I keep getting the error "Cannot find table 3." How in VB can I check if the table exists, rather than my application erroring...

>= not working, R [duplicate]

This question already has an answer here: Why are these numbers not equal? 3 answers I am running the code below. The function Ax returtns the value 1. But the ifelse statement does not recognize that Ax==1. I've tried making the output of the function double-precision and all numeric...

Simple quiz won't wait for an answer

I have been trying to make a simple quiz as part of an online exercise, I have 2 questions with an if statement that should only accept 1 of 3 possible outcomes, the correct answer, the wrong answer or an incorrect selection. My problem is, when the user makes and...