Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

Find the median age of a group of people

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Find the median age of a group of people

    I�m running a statistical report about members of an organization. I have the formula below for finding the average age of members at a given time. This formula works fine. What I�m trying to figure out is how to go about finding the median age for these members.

    The formula below gives me the average of the table, persons, filtered to find the active members whose birthdate is not blank and the average age as of a user supplied date. That date is stored in the variable vDate_Report_End.

    Code:
    tableavg("persons","p_status=\"A\".and.remspecial(dtoc(birthdate))<>\"\" ","age(birthdate,Var->vDate_Report_End)")
    There doesn�t seem to be much at all in the message board. What little I could find, I�m not sure how I could apply it to a report. The table currently has less than 500 recorders but could possible have up to 5000 records.

    Ron
    Alpha 5 Version 11
    AA Build 2999, Build 4269, Current Build
    DBF's and MySql
    Desktop, Web on the Desktop and WEB

    Ron Anusiewicz

    #2
    Re: Find the median age of a group of people

    See if this works. I gave it a minimal test.

    Code:
    FUNCTION tst_mean AS N (tablename AS C)
    	tbl = table.open(tablename)
    	recs = tbl.records_get()
    	tbl.order("birthdate")
    	tbl.fetch_first()
    	if mod(recs,2) = 1 'odd count
    		for qx = 1 to int(recs/2)
    			tbl.fetch_next()
    		next
    		tst_mean = age(tbl.birthdate,date())
    		tbl.close()
    	else
    		for qx = 1 to int(recs/2)-1
    			tbl.fetch_next()
    		next
    		lower_val = age(tbl.birthdate,date())
    		tbl.fetch_next()
    		upper_val = age(tbl.birthdate,date())
    		tbl.close()
    		combined = lower_val+upper_val
    		tst_mean = combined/2
    	end if
    END FUNCTION
    There can be only one.

    Comment


      #3
      Re: Find the median age of a group of people

      Stan,

      Thank you very much.

      I created three layout variables. I then put your modified function into the reports OnPrintInit event. It appears to be working "OK".
      I did put the same data into an excel spreadsheet which did yield slightly different numbers. But then the excel numbers were slightly different from the built in alpha function tableavg.

      alpha avg 43.7 mean 40.5
      excel avg 44.2 mean 41.1

      The test data was only 20 records. I'm not should if rounding could be making the difference.

      Code:
      var->vnActMean = tst_Mean("persons", "A", vDate_Report_Start, vDate_Report_End )	'Active
      var->vnInActMean = tst_Mean("persons", "I", vDate_Report_Start, vDate_Report_End )	'Inactive
      var->vnLeftMean = tst_Mean("persons", "L", vDate_Report_Start, vDate_Report_End)	'Left
      
      FUNCTION tst_mean AS N (tablename AS C, Status as C, sDate as D, Date as D )
      	IF Status = "L" THEN
      		filter = "P_Status="+s_quote(status)+".and.remspecial(dtoc(birthdate))<>\"\".and."+between_date("D_left",sDate,Date)
      	ELSE
      		filter = "P_Status="+s_quote(status)+".and.remspecial(dtoc(birthdate))<>\"\" "
      	END IF
      	
      	tbl = table.open(tablename)
      	query.description = "Mean"
      	query.order = "birthdate"
      	query.filter = filter
      	qry = tbl.query_create()
      	recs = qry.records_get()
      	i = tbl.index_primary_put("Mean")
      	tbl.fetch_first()
      	IF mod(recs,2) = 1 'odd count
      		FOR qx = 1 TO int(recs/2)
      			tbl.fetch_next()
      		next
      		tst_mean = age(tbl.birthdate,date)
      		qry.drop()
      		tbl.close()
      	ELSE
      		FOR qx = 1 TO int(recs/2)-1
      			tbl.fetch_next()
      		next
      		lower_val = age(tbl.birthdate,date)
      		tbl.fetch_next()
      		upper_val = age(tbl.birthdate,date)
      		qry.drop()
      		tbl.close()
      		combined = lower_val+upper_val
      		tst_mean = combined/2
      	END IF
      	
      END FUNCTION
      Again,

      Thank you very much.

      Ron
      Alpha 5 Version 11
      AA Build 2999, Build 4269, Current Build
      DBF's and MySql
      Desktop, Web on the Desktop and WEB

      Ron Anusiewicz

      Comment


        #4
        Re: Find the median age of a group of people

        Ron,

        Pls supply copy of the sample data. Thanks.

        -- tom

        ps. I'm curious why your function reference the mean ? Thought you were looking for the median. The mean <> the median.
        Last edited by Tom Cone Jr; 03-26-2013, 05:53 AM.

        Comment


          #5
          Re: Find the median age of a group of people

          Originally posted by Ronald Anusiewicz View Post
          I did put the same data into an excel spreadsheet which did yield slightly different numbers. But then the excel numbers were slightly different from the built in alpha function tableavg.

          alpha avg 43.7 mean 40.5
          excel avg 44.2 mean 41.1
          Ron:
          Are you looking for "Mean"? or "Median"?
          The title to your thread refers to Median, but this post talks about "Mean".
          Mean and Median are completely two different animals.

          Comment


            #6
            Re: Find the median age of a group of people

            Well, I guess my ignorance of statistics is showing.

            Yes, I was looking for the Median age, not the mean.
            This is just part of a bigger picture where I'm looking for the youngest, oldest, average and median age of members during a given time period.

            For the year 2011, the youngest, oldest, etc....

            Because I'm using real data with personnel information, it would take me some time to put together a sample workspace, but for now I can give you the excel worksheet.

            Ron
            Attached Files
            Alpha 5 Version 11
            AA Build 2999, Build 4269, Current Build
            DBF's and MySql
            Desktop, Web on the Desktop and WEB

            Ron Anusiewicz

            Comment


              #7
              Re: Find the median age of a group of people

              This was a little easier than I thought it would be.

              Here's a workspace example with my real data with private information removed.

              I'm having other issues with the report, but for now, I'm just trying to work on the average and median ages.

              Thanks,

              Ron
              Attached Files
              Alpha 5 Version 11
              AA Build 2999, Build 4269, Current Build
              DBF's and MySql
              Desktop, Web on the Desktop and WEB

              Ron Anusiewicz

              Comment


                #8
                Re: Find the median age of a group of people

                So you want the median.
                The Median is the record right smack in the middle.
                If you have an odd number of records, say 11 records, and if you sort them according to the field in question, then the median is the value of the field in record #6 (not recno, but #6 according to the sort order).
                If you have an even number of records, say 12, then the median is the average value of the two records in the middle, i.e. #6 & #7. The 6th record is preceded by 5 records and the 7th record is followed by 5 records.
                That's how you arrive at the median.
                The question becomes, how do you get to that record (or two records) in the middle of a bunch of records?
                You could do that by many means, but ...what is the shortest cut?
                Well, here is one way:

                The middle record is the top record of the bottom half (or the bottom record of the top half). And when I say half, its half plus one if the total number is odd or the bottom record of the top half and the top record of the bottom half if the total number of records is an even number. Hope you are still with me!

                With that concept in mind, you could write a relatively lengthy expression or design an UDF to do that.

                So, here are your working blocks:
                top_records(1,bottom_records(Num_of_records/2(..with consideration for odd and even..), filter))

                There is a nifty way to calculate this number (in red)..
                Let me see if I could put this in an UDF for you..but I am pretty sure you could do it yourself..
                You could also make use of TOP_RECORDS_LIST()

                Comment


                  #9
                  Re: Find the median age of a group of people

                  My great great grandpa used to say (not to me of course, I wasnt around then)
                  "You can make a programmer out of a mathematician
                  But you cant take the mathematician out of that programmer."

                  (Well he must have meant an abacus programmer)

                  Comment


                    #10
                    Re: Find the median age of a group of people

                    Here's my contribution.

                    I extracted 14 records from the main table and used the smaller table to validate my results.

                    Unzip and extract the files within the attachment to an empty folder.

                    Run Toms_Script to see results in trace window.

                    -- tom

                    Comment


                      #11
                      Re: Find the median age of a group of people

                      Here is another short cut:
                      let's say you have 100,001 that is one hundred thousand and one records that meet the filter..
                      And you want to jump to the record right smack in the middle.
                      What is the shortest cut?
                      Easy:
                      (For convenience and expediency I am illustrating here based on odd number of records, you could modify this to deal with even numbers)
                      First find the rank of the middle record:
                      x=round_up(100001/2,0) 'this=50001
                      So now we want to jump to this record. How?
                      t=table.open(...)
                      t.fetch_first()
                      for i=1 to x step x 'you probably never thought you could replace the step with a variable. I didn't either, but it works.
                      t.fetch_next()
                      next
                      That will get you straight to your desired record, the one in the middle, in one measly step!.
                      Have fun.

                      Comment


                        #12
                        Re: Find the median age of a group of people

                        Here is an untested function. Please test first:
                        Code:
                        FUNCTION Median AS N (tablename AS C, fieldname as C, filter as C )
                        	t=table.open(tablename)
                        	t.query_create("t",filter,fieldname)
                        	cnt=t.records_get()
                        	x=round_up(cnt/2,0)
                        	t.fetch_find(x)
                        	v_median=eval("t."+fieldname)
                        	if mod(cnt,2)=0
                        		x1=t.fetch_next()
                        		v_median=(v_median+eval("t."+fieldname))/2
                        	end if
                        	median=v_median
                        END FUNCTION

                        Comment


                          #13
                          Re: Find the median age of a group of people

                          G,

                          Thanks for your suggestion. Looking at Stan's code, I believe he took that same approach.

                          Tom,

                          Nice code and very well documented. I adapted your code to my live data and my results are now further from the excel spread sheet results.
                          I then populated your test table with the data from my live data and I got the same results.

                          excel 41.1 alpha 42.0 Stan's code gives me 40.5

                          Interesting. I'm not saying your method is wrong, I'm just puzzled as to why the two disagree by so much.
                          Why did you chose to invert the birthdate? It doesn't seem to effect the results as I tried it both ways.

                          I'm not sure the difference is enough to really matter, just curious.

                          In case your interested, I've attached a zip file with toms_tbl.dbf containing the same 20 records that I have been working with, both in Alpha and in excel.

                          Thank you,

                          Ron
                          Attached Files
                          Alpha 5 Version 11
                          AA Build 2999, Build 4269, Current Build
                          DBF's and MySql
                          Desktop, Web on the Desktop and WEB

                          Ron Anusiewicz

                          Comment


                            #14
                            Re: Find the median age of a group of people

                            I'll take a look at what you're doing. I don't know how Excel produces the median value.

                            I inverted the list of ages because its easier for me to validate the results that way, since I'm validating by hand.

                            Comment


                              #15
                              Re: Find the median age of a group of people

                              The correct answer is 42 and is produced both in alpha and Excel.

                              Comment

                              Working...
                              X