Monday, April 30, 2012

R Tips

R! Tips

Thursday, April 26, 2012

Diabetes diet: What to eat when you have diabetes - Chicago Tribune

Decoding the diabetic diet
Source: Chicago Tribune.


"A focus on carb- and portion-control should be top priority, but that doesn't mean the occasional treat is out of the question."


Eat more

  • Fish
  • Nuts
  • Nonstarchy vegetables
  • Magnesium-rich foods (spinach, almonds, broccoli, lentils, tofu, pumpkin seeds, sunflower seeds)
  • Foods rich in omega-3s (flaxseed, walnuts, salmon, tuna, sardines)
  • Whole grains (quinoa, brown rice, wild rice, amaranth)
  • Whole fruit (in servings the size of a tennis ball)
  • Nonfat or low-fat Greek yogurt
  • Olive oil
  • Cinnamon
  • Vinegar

Eat less

  • Stick margarine, butter, shortening or lard
  • Fried foods
  • Refined grains (white bread, white rice, white flour)
  • Sugary drinks (soda, fruit juices, sweetened ice teas, sports drinks)
  • Fruity yogurts
  • High-fat meats (sausage, bacon, hot dog, scrapple)

Full text here.

Tuesday, April 24, 2012

Matrix of Stata

Matrix of Stata
  • Define a -matrix- or -mat- in short: matrix matrixname = matrix_expression.
    • matrix define mymat = (1,2\3,4)
    • Or, matrix mymat = (1,2\3,4)
    • mat list mymat
  • Print a matrix: 
    • matrix list matrix_name
  • -matlist-: Display a matrix and control its format: 
    • matlist r(table)'*100, tw(20) format(%8.2f)
  • Matrix rename: .matrix rename oldname newname
  • Rename col/row names: 
    • matrix colnames A = names
    • matrix rownames A = names
  • Convert variables to matrix and vice versa: 
    • Matrix addition & subtraction:
      • mat matrix_a + matrix_b
      • mat matrix_a - matrix_b
    • Matrix multiplication:
      • mat matrix_a * matrix_b
    • Transpose of a matrix
      • mat matrix_t matrix_a'
    • Inverse of a matrix, matrix function are defined by using parentheses ():
      • mat matrix_inv = inv(matrix_a)
    • A\B adds row of B after the rows of A; A,B adds columns B to matrix A. For example:
      • mat RTab=r(table)'
      • mat R1=RTab[1...,"b"]
      • mat R2=RTab[1...,"ll".."ul"]
      • mat RDisp=R1,R2
    • The usual way to obtain matrices after a command that produces matrices is simply to refer to the returned matrix in the standard way. (source: Stata manual) Or 'get()' matrix function obtains a copy of an internal Stata system matrix.
      • For instance all estimation commands return
        • e(b) coefficient vector
        • e(V) variance-covariance matrix of the estimates (VCE)
      • And these matrices can be referenced directly. For examples:
        • matrix list e(b)
        • mattrix myE = e(b)*100
        • matrix myV = e(V)*100
        • matrix myVget=get(_b)
      • Then, you can use
        • "ereturn post myE myV" to Change coefficient vector and variance-covariance matrix.
        • And "ereturn display" to create and display a coefficient table: "r(table)" that have been previously posted using "ereturn post" or "repost". "r(table)" is a matrix containing all the data displayed in the coefficient table (including b, se, t, pvalue, ll, ul, df, crit, and eform).
    • Reset row/column names of matrix
      • mat A = (1,2,3\ 4,5,6\ 7,8,9)
      • matrix rownames A = myrow1 myrow2 myrow3
      • mat colnames A = mycol1 mycol2 mycol3
      • refix the column names of A with equation names eq1, eq2, and eq3: mat coleq A = eq1 eq2 eq3
    • Matrix utilities:
      • matrix dir - List the currently defined matrices
      • matrix list - Display the contents of a matrix
      • matrix rename - Rename a matrix
      • matrix drop - Drop a matrix
    • Matrix Subscripting:
      • Referring to a matrix's element/cell using numbers of row and column or using the names of row and column or using mixed ways:
        • disp matrix_name [r,c]
        • matrix A = A/A[1,1]
        • gen newvar = oldvar/A[2,2]
        • mat B = V["price","price"]
        • gen sdif = dif/sqrt(V["price","price"])
      • Create a matrix B having the first through fifth rows and first through fifth columns of A, using two periods:
        • matrix B = A[1..5,1..5]
      • Create a matrix B having the all rows and first column of A, use three periods: 
        • matrix B = A[1...,1]
        • mat B=A[1...,"b"]
      • Define an element of a maxtrix:
        • mat A[1,2] = sqrt(2)
    • Abstract row and column names from a matrix (-rownames- and -colnames-: Macro extended function related to matrices). Also, we can use -rowfullnames matname-, and -colfullnames matname-
      • sysuse auto,clear
      • regress mpg price weight length
      • local rn :rownames r(table)
      • local cn :colnames r(table)
      • disp "`w1'" // price
      • disp "`:word 1 of `:colnames r(table)''" // price
      • disp "rownames = `rn'" _n "columnnames = `cn'"
      • disp `:word count `cn'' // 4
      • disp "`:word count `:colnames r(table)''" // 4
      • disp "`:colsof r(table)'" // 4
      • disp "`:rowsof r(table)'" // 9
      • forval i = 1/`:word count `cn'' {
      •   local varn: word `i' of `cn'
      •   disp "`varn'"
      •   }
    • Find out number of row and column (-colsof(matname)- and -rowsof(matname)-): Matrix functions
      • disp "number of row = " rowsof(r(table)) 
      • disp "number of column = " colsof(r(table)) 
    • How to do element-by-element operation
      • mata, the new matrix language of Stata (since version 9), can do element-by-element operation easily. (read more here)
      • Colon operations perform element-by-element operations: addition(:+), subtraction(:-), multiplication(:*), division(:/), power(:^), equality(:==), inequality(:!=), greater than(:>), greater than or equal to(:>=), less than(:<), less than or equal to(:<=), and(:&), or(:|)
      • If you apply the exponential function on each element:
        • . mata
        • : x=(0,1\2,3)
        • : exp(x) // x = (1,2.7\7.4,20.1)
        • : exp((0,1\2,3)) // (1,2.7\7.4,20.1)
        • : x:/2 // x = (0,0.5\1, 1.5)
        • : end
      • mata can use a Stata matrix
        • matrix A=r(table)'
        • mata: exp(st_matrix("A")) // display only
        • mata: st_matrix("se",sqrt(diagonal(st_matrix("V")))) // create a matrix of standard deviation
        • mata: st_matrix("expA", exp(st_matrix("A"))) // create a new matrix, expA
        • matrix eformtab=expA[1..., "b"], expA[1...,"ll".."ul"], expA[1...,"se"]
        • matlist eformtab*100, tw(30) format(%8.1f)
    • More about mata
      • create row vector: row=(1,2,3) or row=(1..3)
      • create column vector: col=(1\2\3) or col=(1::3)
      • transpose a matrix: m2=(0,1\2,3)'
      • scalar functions will operate on elements: sqrtrow=sqrt(row)
      • SSCC: an introduction to Mata

    Friday, April 20, 2012

    quantile regression

    Percentile and Quantile Regression for Complex Survey Data

    R!
                > library(survey)
                > options(survey.lonely.psu="remove")
                > dclus1<-svydesign(id=~psu_p, strata=~strat_p, weights=~wtfa, nest=TRUE, data=nhis)
                > bclus1<-as.svrepdesign(dclus1,type="bootstrap", replicates=100)
                > withReplicates(bclus1, quote(coef(rq(api00~api99, tau=0.5, weights=.weights))))
    • Survey analysis in R by Thomas Lumley.
    • How to deal with singleton/lonely PSUs (How do I analyze survey data with a stratified design with certainty PSUs?):
      • Default: - options(survey.lonely.psu="fail") -, which makes it an error to have a stratum with a single, non-certainty PSU. 
      • options(survey.lonely.psu="remove") -,and - options(survey.lonely.psu="certainty") -, which can be set after the - library(survey)- mean a single-PSU stratum makes no contribution to the variance.
      • - options(survey.lonely.psu = "adjust") -, which is taking the average of all the strata with more than one PSU. This might be appropriate if the lonely PSUs were due to data missing at random rather than to design deficiencies.
      • Difficulties in estimating variances also arise when only one PSU in a stratum has observations in a particular domain or subpopulation. R gives a warning rather than an error when this occurs, and can optionally apply the "adjust" and "average" corrections. To apply the corrections, set - options(survey.adjust.domain.lonely=TRUE) -, and set - options(survey.lonely.psu="xxx") - to the adjustment method you want to use.
    Stata
    • Quantile regression
    • Stata: How do I obtain percentiles for survey data?
    • If only need point estimates of quantiles: we can use "_pctile" (store them in r()), "pctile" (create variables containing percentiles), and "xtile" (create variable containing quantile categories) to get quantiles for survey data. Or use "qreg"
      • webuse nhanes2
      • _pctile height [pw=finalwgt], p(10,90)
        • return list
        • disp "Median of age = " scalar(r(r1))
      • pctile qhgt=height [pw=finalwgt], nq(4) genp(percent)
      • xtile hgtdec=height[pw=finalwgt], nq(10)
      • table sex [pweight= finalwgt] , c(median age count age) row format(%9.0f)
      • qreg height [pw=finalwgt], quantile(10)
      • mi estimate: qreg height, quanitle(10) vsquish
    • If need standard errors and CIs, use user-written command "epctile" ("findit epctile")(or directly from "net from http://members.socket.net/~skolenik/stata/").
      • webuse nhanes2
      • svyset psu [pw=finalwgt], strata(strata)
      • epctile height, p(10) svy
      • epctile height, percentiles(10 20 30 50) subpop(if sex==1) svy
      • Or, see my update (3/3/2017) below
    • Replicate Weights and Bootstrap sampling and estimation.
    • May use bootstrap to get variances of a complex designed sample: -bsweights- (IDEAS)creates the bootstrap weights for designs specified through and supported by svy:
      • bs4rw, rw(brrrwt*): qreg weight i.race if subpop==1 [pw=finalwgt], q(.75)
    • Started from version 13, -qreg- supports -pweight- and -iweight-. The 'bootstrap' has 'strata()' etc. options, even though 'bootstrap' is not designed for the complex survey data, the estimates are very similar to the estimates from the "withReplicates(design=xxx, quote(coef(rq(y ~ x,tau=0.5, weights=.weights))))" of R!.
    • Blog: Doing Bootstrap/Jackknife in Stata for complex survey data
    • Updates(3/3/2017): The better approach is to use 'svy jackknife' or 'svy bootstrap' with jackknife or bootstrap replicate weights. After the version 10, you don't need create jackknife replicate weights using user-written command -survwgt-, the -svy jackknife- can create the weights according to the info provided by -svyset-. You do need provide the bootstrap replicate weights for -svy bootstrap-, which can be created using the user-written command such as -bsweights-:
        • webuse nhanes2, clear
        • svyset psu [pw=finalwgt], strata(strata)
        • bsweights bs_, n(-1) reps(50) seed(4881269)
        • svyset [pw=finalwgt], bsrw(bs_*)
        • svy bootstrap _b: qreg weight i.race, q(.5)
    SAS
    Articles

    When It Comes To A1C Blood Test For Diabetics, One Level No Longer Fits All

    by Nancy Shute

     … If there's one thing that people with diabetes get pounded into their heads, it's that they've got to keep their A1C level under control. That's the blood glucose measure that's used to decide how well a person is managing their diabetes.

    But new diabetes management guidelines announced today will cut many people with diabetes some slack.

    Where old guidelines from the American Diabetes Association said that people should maintain an A1C of 7, the new guidelines say that patients should work with their doctors to determine an appropriate A1C target. …

    Full text: here

    Thursday, April 19, 2012

    Social Rank Affects Monkey Immunity

    Social Rank Affects Monkey Immunity
    Source: The Scientist


    "... the immune effects of rank were not permanent. Seven monkeys that changed rank showed a rapid change in gene expression to match their new status. The finding suggests that health depends on social status, and not vice versa...."


    Full text: here
    Original research article: here

    Wednesday, April 18, 2012

    Let Them Eat Dirt - The Scientist

    Let Them Eat Dirt
    Source: The Scientist

    I read this interesting article with great interest. It demonstrates the rightness of the view of my mom, grandma, great grandma, ..., all of them is/were not scientist for sure.
    "...Maybe it's okay to let your toddler lick the swing set and kiss the dog. A new mouse study suggests early exposure to microbes is essential for normal immune development, supporting the so-called "hygiene hypothesis" which states that lack of such exposure leads to an increased risk of autoimmune diseases. Specifically, the study found that early-life microbe exposure decreases the number of inflammatory immune cells in the lungs and colon, lowering susceptibility to asthma and inflammatory bowel diseases later in life. ..."

    Full text: here

    Tuesday, April 17, 2012

    Tools for Innovative Thinking in Epidemiology

    By Roberta B. Ness

    “Innovation is the engine of scientific progress. Concern has been raised by the National Academies of Science about how well America is sustaining its ‘‘creative ecosystem.’’ In this commentary, the author argues that we can all improve our ability to think innovatively through instruction and practice. The author presents a series of tools that are currently being taught in a curriculum developed at the University of Texas, based on earlier evidence-based creativity training programs. The tools are these: 1) finding the right question; 2) enhancing observation; 3) using analogies; 4) juggling induction and deduction; 5) changing your point of view; 6) broadening the perspective; 7) dissecting the problem; 8) leveraging serendipity and reversal; 9) reorganization and combination of ideas; 10) getting the most out of groups; and 11) breaking out of habitual expectations and frames. Each tool is explained using examples from science and public health. It is likely that each of us will identify with and agree with the usefulness of one or two of the tools described. Broader mastery of many of these tools, particularly when used in combination, has provided our students with a powerful device for enhancing innovation.”

    Read full text here

    Monday, April 16, 2012

    John Glenn's true hero - CNN.com

    John Glenn's true hero
    Source: CNN.com
    "...For half a century, the world has applauded John Glenn as a heart-stirring American hero. He lifted the nation's spirits when, as one of the original Mercury 7 astronauts, he was blasted alone into orbit around the Earth; the enduring affection for him is so powerful that even now people find themselves misting up at the sight of his face or the sound of his voice.
    But for all these years, Glenn has had a hero of his own, someone who he has seen display endless courage of a different kind:
    Annie Glenn.
    They have been married for 68 years.
    He is 90; she turned 92 on Friday.
    This weekend there has been news coverage of the 50th anniversary of Glenn's flight into orbit. We are being reminded that, half a century down the line, he remains America's unforgettable hero. ..."

    The full text here.

    Friday, April 13, 2012

    The Mediterranean Diet

    The Mediterranean Diet

    Dr. Eduardo Farinaro from Federico II University of Naples, Italy, gave us a great presentation about the lifestyle and CHD prevention. I learned more about the Mediterranean diet.

    What is the Mediterranean Diet?
    There may be no single Mediterranean diet; the Mediterranean diet is the traditional dietary patterns of Spain, southern Italy, Greece and specifically the Greek island of Crete, and parts of the Middle East. The major characteristics are a few I remember:
    • olive oil as a principle source of fat.
    • colorful veggies, and fruits, beans & nuts (legumes), and whole grains.
    • regular fish consumption.
    • herb and spicy seasonings, which will reduce the need of salt and fat.
    • moderate drink of wine with the meal. 
    Dr. Farinaro also mentioned the persons living in the Mediterranean diet area are also with lower level of anxiety, having a good relationship with family, and moderate physical activity. He did not mention much about dairy products.

    Mediterranean diet - Wikipedia, the free encyclopedia

    Advanced Query Syntax


    …”The Advanced Query Syntax (AQS) is used by WDS to help users and programmers better define and narrow their searches. Using AQS is an easy way to narrow searches and deliver better result sets. Searches can be narrowed by the following parameters:
    • File kinds: folders, documents, presentations, pictures and so on.
    • File stores: specific databases and locations.
    • File properties: size, date, title and so on.
    • File contents: keywords like "project deliverables," "AQS," "blue suede shoes," and so on.
    Furthermore, search parameters can be combined using search operators. The remainder of this section explains the query syntax, the parameters and operators, and how they can be combined to offer targeted search results. The tables describe the syntax to use with WDS, as well as the properties that can be queried for each file kind displayed in the Windows Desktop Search results window.”…

    How to enable  Advanced Query Syntax search:
    • Go to  Windows Explorer.
    • Click menu “Organize”.
    • Click “Folder And Search Options”.
    • Click “Search” tab.
    • Check “Use Natural Language Search”
    Using Advanced Query Syntax To Find Files in Windows 7 


    Wednesday, April 11, 2012

    Collected Websites and Online Tools

    Collected Websites and Online Tools (obsolete)
    Epidemiology and Statistics
    • Education
    • Inspiration
      • TED is a set of annual conferences that brings together some of the world's best and brightest thinkers to deliver talks on their realms of expertise.
      • TEDMED is a community of people who are passionate about imagining the future of health and medicine.
    • Travel
      • The Roadtrippers road trip planner helps you discover, book, and create travel itineraries of the best places and experiences along the way. Also, there are apps for handhold devices.
      • The airbnb helps you to rent unique places to stay from local hosts in 190+ countries.
      • Hipmunk lets you search for flights across major airlines, giving you easy-to-scan results in a grid sorted by agony ("a combination of price, duration and number of stops").
    • Money Saving
      • FatWallet: Save with coupons and deals - get cash back
      • Clark Howard: Advice You Can Trust. Money in Your Pocket
      • Caslist provides local classifieds and forums for jobs, housing, for sale, personals, services, local community, and events.
      • Car shopping: if you are looking for a car, you might visit these websites to get a good price:
        • Truecar, a hassle-free car-buying experience from a nationwide network of certified dealers.
        • U.S. News Best Cars, a best car, truck and SUV rankings and reviews from U.S. News.
        • Kelley Blue Book.
        • Edmunds - New cars, used cards, car reviews and car prices.
    • Health
    • File Utility
      • Smallpdf is a fast and powerful online converter; it can convert in both ways between PDF and files of MS-Office, also can compress PDF, unlock, merge and split PDF. There is no limits to file size, no ad watermarks - just a free and simple online PDF converter.
      • Any2DjVu Server is offered by DjVu Zone to convert pdf etc. into documents in DjVu format.
      • Extractpdf.com can extract Images, Text or EVEN Fonts from a PDF File.
      • Zamzar is an online format converter which allows to convert media between different formats. It can convert document, music, videos, images, and even archived files. The free service provides a file size up to 100 MB file size limit. It converts MOBI file quite well.
      • TransferBigFiles is helpful to send and receive files that are too big for email attachments. The free account allows you to send files that are as big as 100 MB.
      • SendThisFile can send a big file up to 2 GB for free, but you need create an account.
      • Dropbox has much more features but also can be used for big file transfer.
    • GPS
    • Miscellaneous
      • Copy-and-paste the URL on SaveFrom.net to download files from Rapidshare, FileFactory, Youtube, Google, and Metacafe. For Youtube, you can simply add "ss" after "http://" to download the video.
      • Mr. Number controls who can call you and when with status, blocking, and caller ID for mobile phones.
      • Video conference/chat
      • Zendesk is a calming music source.
      • Grooveshark is a great place to listen to music
      • OpenDNS is the leading provider of Internet security and DNS services. It  protects kids from online violence, pornography, and other unsavory Web material.
      • How to make your own Rivnut tool and install the Pilot running board by yourself:
      • Online Color Palettes Generator
        • PHOTOCOPA from ColourLovers is an advanced color palette tool that helps you create the perfect color palette.
        • Pictaculous is a simple color palette generator and give you HTML hex codes.
        • Kuler by Adobe is a web-hosted application for generating color themes.
        • Color hunter creates and finds color palettes made from images
        • Color Palette Generator can generate a color palette based on an online image.
        • Color Scheme Designer allows you to create various color schemes and export them.
        • You can also use GIMP (Filters/Blur/Pixelize..., or to open the Palettes dialog, go to Windows > Dockable Dialogs > Palettes, then right-click anywhere in the Palettes, select import, the palette file (*.gpl) can be find under a palette folder.) to create one.

    Friday, April 06, 2012

    Choosing Wisely

    Choosing Wisely
    Choosing Wisely aims to promote conversations between physicians and patients by helping patients choose care that is:
    • Supported by evidence
    • Not duplicative of other tests or procedures already received
    • Free from harm
    • Truly necessary

    Wednesday, April 04, 2012

    How to Convert Google Maps Direction into GPX file

    How to Convert Google Maps Direction into GPX file
    • Go to Google Maps and get the direction.
    • Click ‘Link’ (chain shape icon) at the right-upper corner of left panel.
    • Copy the URL (press Ctrl-C).
    • Go to GPSVisualizer.
    • Click ‘Convert to GPX’ under ‘To set more options, use the detailed input pages:’.
    • Select ‘GPX’ under ‘Output format: ’.
    • Paste the URL (press Ctrl-P) under ‘Or provide the URL of a file on the Web:’.
    • Click ‘Convert’.
    • Click the linkage labeled as ‘Click to download xxx.gpx’ to save the converted GPX file.

    Now, you can upload the GPX file to a GPS unit.

    Tuesday, April 03, 2012

    Study Says DNA’s Power to Predict Illness Is Limited - NYTimes.com

    Study Says DNA's Power to Predict Illness Is Limited
    By Gina Kolata of the New York Times
    ...
    If every aspect of a person's DNA is known, would it be possible to predict the diseases in that person's future? And could that knowledge be used to forestall the otherwise inevitable?
    The answer, according to a new study of twins, is, for the most part, "no."
    ...

    Full Text: here
    Original Research Article: The Predictive Capacity of Personal Genome Sequencing