Friday, March 11, 2011

Another R-package to draw heatmap

pheatmap package on CRAN allows you to draw nice heatmaps - especially it allows you to control the cell size.

pheatmap(matrix, scale="row", cluster_cols=FALSE, cluster_rows=FALSE, cellwidth=10, cellheight=10, fontsize=8)

Tuesday, September 07, 2010

Generating random numbers in R

Original link : http://blog.revolutionanalytics.com/2009/02/how-to-choose-a-random-number-in-r.html


Generate a random number between 5.0 and 7.5

If you want to generate a decimal number where any value (including fractional values) between the stated minimum and maximum is equally likely, use the runif function. This function generates values from the Uniform distribution. Here's how to generate one random number between 5.0 and 7.5:

> x1 <- runif(1, 5.0, 7.5)
> x1
[1] 6.715697

Of course, when you run this, you'll get a different number, but it will definitely be between 5.0 and 7.5. You won't get the values 5.0 or 7.5 exactly, either.

If you want to generate multiple random values, don't use a loop. You can generate several values at once by specifying the number of values you want as the first argument to runif. Here's how to generate 10 values between 5.0 and 7.5:

> x2 <- runif(10, 5.0, 7.5)
> x2
[1] 6.339188 5.311788 7.099009 5.746380 6.720383 7.433535 7.159988
[8] 5.047628 7.011670 7.030854

Generate a random integer between 1 and 10

This looks like the same exercise as the last one, but now we only want whole numbers, not fractional values. For that, we use the sample function:

> x3 <- sample(1:10, 1)
> x3
[1] 4

The first argument is a vector of valid numbers to generate (here, the numbers 1 to 10), and the second argument indicates one number should be returned. If we want to generate more than one random number, we have to add an additional argument to indicate that repeats are allowed:

> x4 <- sample(1:10, 5, replace=T)
> x4
[1] 6 9 7 6 5

Note the number 6 appears twice in the 5 numbers generated. (Here's a fun exercise: what is the probability of running this command and having no repeats in the 5 numbers generated?)

Select 6 random numbers between 1 and 40, without replacement

If you wanted to simulate the lotto game common to many countries, where you randomly select 6 balls from 40 (each labelled with a number from 1 to 40), you'd again use the sample function, but this time without replacement:

> x5 <- sample(1:40, 6, replace=F)
> x5
[1] 10 21 29 12 7 31

You'll get a different 6 numbers when you run this, but they'll all be between 1 and 40 (inclusive), and no number will repeat. Also, you don't actually need to include the replace=F option -- sampling without replacement is the default -- but it doesn't hurt to include it for clarity.

Select 10 items from a list of 50

You can use this same idea to generate a random subset of any vector, even one that doesn't contain numbers. For example, to select 10 distinct states of the US at random:

> sample(state.name, 10)
[1] "Virginia" "Oklahoma" "Maryland" "Michigan"
[5] "Alaska" "South Dakota" "Minnesota" "Idaho"
[9] "Indiana" "Connecticut"

You can't sample more values than you have without allowing replacements:

> sample(state.name, 52)
Error in sample(state.name, 52) :
cannot take a sample larger than the population when 'replace = FALSE'

... but sampling exactly the number you do have is a great way to randomize the order of a vector. Here are the 50 states of the US, in random order:

> sample(state.name, 50)
[1] "California" "Iowa" "Hawaii"
[4] "Montana" "South Dakota" "North Dakota"
[7] "Louisiana" "Maine" "Maryland"
[10] "New Hampshire" "Rhode Island" "Texas"
[13] "Florida" "North Carolina" "Minnesota"
[16] "Arkansas" "Pennsylvania" "Colorado"
[19] "Idaho" "Connecticut" "Utah"
[22] "South Carolina" "Illinois" "Ohio"
[25] "New Jersey" "Indiana" "Wisconsin"
[28] "Mississippi" "Michigan" "Wyoming"
[31] "West Virginia" "Alaska" "Georgia"
[34] "Vermont" "Virginia" "Oklahoma"
[37] "Washington" "New Mexico" "New York"
[40] "Delaware" "Nevada" "Alabama"
[43] "Kentucky" "Missouri" "Oregon"
[46] "Tennessee" "Arizona" "Massachusetts"
[49] "Kansas" "Nebraska"

You could also have just used sample(state.name) for the same result -- sampling as many values as provided is the default.

Further reading

For more information about how R generates random numbers, check out the following help pages:

> ?runif
> ?sample
> ?.Random.seed

The last of these provides technical detail on the random number generator R uses, and how you can set the random seed to recreate strings of random numbers.

Tuesday, July 20, 2010

Running Geneset enrichment analysis on commandline

java -cp /stor1/shah/Ruben_peptide/gsea_analysis/gsea2-2.06.jar
-Xmx2000m xtools.gsea.Gsea
-res foo_expression_values.gct
-cls foo_expression_values.cls#Normal_versus_Treatment
-gmx msigdb.v2.5.symbols.gmt -chip HG_U133_Plus_2.chip
-collapse true -mode Max_probe -norm meandiv -nperm 1000
-permute phenotype -rnd_type no_balance -scoring_scheme weighted
-rpt_label my_analysis -metric Signal2Noise -sort real -order descending -include_only_symbols true -make_sets true -median false -num 100
-plot_top_x 20 -rnd_seed timestamp -save_rnd_lists false -set_max 500 -set_min 15 -zip_report false -out /stor1/shah/Ruben_peptide/gsea_analysis -gui false

commandline for GSEA.

Monday, July 19, 2010

Significance of overlapping gene lists

Wen Fury and Wentian Li
http://www.nslij-genetics.org/wli/pub/ieee-embs06.pdf

To identify significance of overlap for two differentially expressed gene sets n1 and n2 (e.g. d1-n1 and d2-n1) use either hypergeometric or Fisher's exact test p-value.

Given integers n, n1, n2, m (max(n1,n2) <= n and m <= min (n1,n2)), the hypergeometric distribution is defined as

P(m) = [C(n1, m) * C (n - n1, n2 -m)]/ C (n, n2)

where C(n,m) is the number of possibilities of choosing m objects out of n objects : C (n,m) = n!/[m! (n -m)!]

It is usually more interesting to calculate the sum of P(m) for m's equal or larger than the observed value (i.e. p-value) :


p-value = Sigma [k= m to min (n1,n2)] p(k)
= Sigma [k = 0 to min (n1,n2)] p(k) - Sigma [k = 0 to m - 1] p(k)

For calculating it in R use :

if m = 0, p-value = 1

phyper (m, n1, n - n1, n2):
p-value = phyper(min(n1,n2), n1, n-n1, n2) - phyper(m-1, n1, n-n1, n2) if m > 0

One can also use Fisher's exact test on the following 2-by-2 table:

col1 col2 total
row1 m n1-m n1
row2 n2-m n-n1-n2+m n - n1
total n2 n-n2 n

They produce identical results.

Thursday, July 08, 2010

From a logical matrix to numerical matrix

Que : From a matrix of TRUE/FALSE get a matrix of 0 and 1
Ans : Multiply the logical matrix by self

Monday, April 26, 2010

Removing all NA rows and columns

Removing all NA rows and/or columns

fsFit[-which(apply(fsFit,1,function(x)all(is.na(x)))),-which(apply(fsFit,2,function(x)all(is.na(x))))]

Wednesday, April 21, 2010

extracting a percentage of data by random by groups

1) Randomly choose 10% of data from each "age" group.

> x <- data.frame(group=sample(1:4,100,TRUE), age=runif(100,4,80))
> tapply(x$age, x$group, function(z) mean(z[sample(seq_along(z), length(z) / 10)]))


2) To split my dataset randomly into 2 parts: a prediction set (with 2/3 of my data) and a validation set (with 1/3 of my data).

> x <- 1:100 # test data
> y <- split(x, sample(1:2, length(x), replace=TRUE, prob=c(1,2)))

3) I would like to randomly divide this data frame in half. how to select those rows that were not selected and assign them to randomsample2

selected<-rep(0,39622)
selected[sample(1:39622,39622/2)]<-1
data$selected<-selected
rm(selected)
or
data$selected<-rbinom(39622,1,.5)

extracting a percentage of data by random by groups

Motivating example:

If I have a dataframe with one of the variables called "age" for
example, and I want to extract a random 10% of the observations from
each "age" group of the entire data frame.

> set.seed(23) # on Windows
> dat <- data.frame(age = factor(sample(1:4, 200, rep = T)), y = runif(200))
> head(dat) # ages are in random order

age y
1 3 0.64275524
2 1 0.56125314
3 2 0.82418228
4 3 0.97050933
5 4 0.02827508
6 2 0.72291636

> with(dat, table(age)) # how many in each age group
age
1 2 3 4
37 55 44 64

> ind <- lapply(split(1:nrow(dat), dat$age),
function(x) sample(x, round(length(x)/10))) # the trick

> ind
$`1`
[1] 135 2 188 133

$`2`
[1] 124 33 140 162 25 13

$`3`
[1] 115 79 27 44

$`4`
[1] 58 129 84 198 72 109

> sample_dat <- dat[sort(unlist(ind)), ] # with indices, select data

> sample_dat
age y
2 1 0.5612531
13 2 0.7339141
25 2 0.9548750
27 3 0.7419931
33 2 0.6965722
44 3 0.5363812
58 4 0.5464051
72 4 0.2785669
79 3 0.6453164
84 4 0.1203811
109 4 0.9154706
115 3 0.2118767
124 2 0.3056171
129 4 0.7635097
133 1 0.6474702
135 1 0.2466226
140 2 0.6292326
162 2 0.5338671
188 1 0.9882631
198 4 0.1983350
>

Sunday, April 18, 2010

Extract rows from data frame based on row names from anotherdata frame

Found in google searches .. can be useful

#Create data and data frames
x=rnorm(5,0,1)
y=rnorm(5,0,1)
z=rnorm(5,0,1)
d1=data.frame(x,y)
d2=data.frame(y,z)

#which variable name in d2 is a variable name in d1?
names(d2[names(d2)%in%names(d1)]) # it's y

#give me the columns of d2 that have variable names
#that are also variable names in d1

d2[names(d2)==names(d2[names(d2)%in%names(d1)])]

#check
d2$y

# continuing with example:

rownames(d1)<- letters[1:5]
rownames(d2)<- letters[3:7]

# and then for rownames of d1 that are also in rownames of d2:
# for the full rows ...

d1[row.names(d1) %in% row.names(d2),]

# or for just the names:

rownames(d1)[row.names(d1) %in% row.names(d2)]

Friday, March 05, 2010

Merge two data frames and order according to a column...

find_annotations_for_non_overlaping_probes <- function
(probeList, annotations, expressedList1) {

annotationIdx <- match(probeList, annotations[,1])
pvalueIdx1 <- match (probeList, expressedList1[,4])

id1 <- as.data.frame(expressedList1[pvalueIdx1,])
id3 <- as.data.frame(annotations[annotationIdx,])

rownames (id1) <- probeList ;
colnames(id1) <- c("rawp", "adjp", "index", "probeId")
rownames (id3) <- probeList

resultOut <- data.frame(merge(id1, id3, by = "row.names"), row.names = 1)
resultOut.sorted <- resultOut[do.call(order, resultOut[1]),]
}

Wednesday, March 03, 2010

Writing R-plots into different devices

pdf("foo.pdf")

plot(x)
dev.off()

Other possibilities are jpeg(), tiff(), postscript() etc.

Setting up aroma.affymetrix for analysis

Setting up aroma.affymetrix for analysis two directories : rawData and annotationData
from where aroma is launched

rawData/cancer_name/HuGene-1_0-st-v1/*.CEL
annotationData/chipTypes/HuGene-1_0-st-v1/*.cdf
annotationData/chipTypes/HuGene-1_0-st-v1/NetAffx/*.csv

Wednesday, January 13, 2010

RLE AND NUSE plots

Affy QC plots for exon arrays ...

One method of deciding whether or not an array is problematics from a quality standpoint is NUSE. The goal of NUSE is to identify any arrays which have elevated standard errors relative to other arrays in the dataset. This is done by standardizing the SE across arrays to have median 1 for each probeset. Our graphical tool consists of boxplots of these quantities for each array. A discordant boxplot indicates it is of poorer quality relative to the rest of the dataset. Instead of visually examining these quantities suitable numerical summaries such as the median and IQR NUSE could be used.

Another tool for making a decision about whether an array should be removed from subsequent analysis because of poor quality is RLE. These are the log-scale expression values relative to the median expression value computed on a probeset by probeset basis. a significantly different boxplot indicates problem.

aroma.affymetrix and other lots of packages allows to plot RLE and NUSE.

The NUSE is generally considered more sensitive than the RLE.

Friday, December 11, 2009

Test about a single proportion for categorical data

Ho: Pi = Pio vs. HA: Pi NA Pio

Wald Test: Z = Pi-hat - Pio/ sqrt (Pi-hat (1 - Pi-hat)/n)

Score Test : Z = Pi-hat - Pio/ sqrt (Pio (1 - Pio)/n)

Score test is slightly more powerful in distinguising evidence against Ho.


R-code for score test : prop.test (27, 922, p=0.02, correct =FALSE)

Here is p is the population probability. and 27 is the observed instance of some phenomena in population. 27/922 will give Pi-hat - the binomial estimate in sample.
Its a Chi-square test on 1 degree of freedom.

Here the p-value is 0.0440 - where the Ho is rejected and 27/922 = 0.029 is NA to 0.02.

Obtaining Confidence Intervals
===============================

The Wald Confidence Interval for single proportion can be obtained by inverting the Wald test statistic but it falls into problem if n is small or Pi is small.

A Score CI can be used in this case.

The R-code is

Wald

library(Hmisc)

binconf(27,922,method="asymptotic")

PointEst Lower Upper
0.02928416 0.01840125 0.04016708


Score (Wilson):

binconf(27,922,method="wilson")

PointEst Lower Upper
0.02928416 0.02020271 0.04227177

prop.test also give the score CI.

========================

In case observed events are small in number and normality assumption is not valid.
One can use binomial exact test to calculate the p-value and CI.

binom.test(3, 58, p = 0.02,
+ alternative = "two.sided",
+ conf.level = 0.95)
Exact binomial test
data: 3 and 58
number of successes = 3, number of trials = 58,
p-value = 0.1101
alternative hypothesis: true probability of success
is not equal to 0.02
95 percent confidence interval:
0.01079648 0.14380463
sample estimates:
probability of success
0.05172414

Tuesday, December 08, 2009

R-packages unix to windows

Use

http://win-builder.r-project.org/upload.aspx

Make sure MAINTAINER has your email address. The site should send instructions on downloading the windows version of the package.

Monday, December 07, 2009

Bioconductor post on using arrayQualityMatrics with exon arrays

Looks like both simpleaffy and arrayQualityMetrics have problem with QCing Affy Exon 1.0 ST arrays.

Though following post does suggest a way to put custom CDF.


Hi Gard,

Sorry for the delay answering. I do not have much experience using
arrayQualityMetrics for Exon arrays, so I have talked with Crispin Miller
(simpleaffy package) about it and according to him "most of the Affymetrix
QC metrics for the 3' IVT arrays aren't directly applicable to the exon
arrays. They rely on MAS 5 and paired MM spots (neither of which are
applicable for exon arrays) and also make assumptions on 3'/5' ratios that
don't apply because the exon array chemistry is different."
I have now modified the package and version 2.4.3 of arrayQualityMetrics
should not perform the QC statistics from simpleaffy when "exon" is in the
cdfname.

Best wishes,
Audrey

> Hi.
>
> I am trying to get the arrayQualityMetrics package to run on a set of
CEL files from the Human Exon array from Affymetrix
>
> My problems begin when I want to run the arrayQualityMetrics function
and it gives the following error message :
>
> running R 2.9.2 and bioconductor version 2.4
>
> >library(affy)
> >library(simpleaffy)
> >ibrary(arrayQualityMetrics)
> >ecesbatch<-read.affybatch("H1.CEL", "H2.CEL", "H3.CEL", "H4.CEL",
> "H5.CEL", "H6.CEL", "H7.CEL", "H8.CEL", "H9.CEL", "H10.CEL",
> "H11.CEL", "H12.CEL", "H13.CEL", "H14.CEL", "H15.CEL", "H16.CEL")
>
> ## attach cdf to expr set
> ecesbatch cdfName <- "exon.pmcdf" ## this is a cdf file from the XMAP
website
>
> #Check the name is correct for the cdf file (unneccessary)
> > cdfname <- cleancdfname(cdfName(ecesbatch))
> > cdfname
> [1] "exon.pmcdf"
>
> >arrayQualityMetrics(expressionset = ecesbatch,outdir =
> "output",force = TRUE,do.logtransform = TRUE)
>
> This cmd runs for a very long time and generates a bunch of .pdfs and
.pngs and an empty QCReport.html file.
> And R says there is an error sonce the arrayQualityMetrics package does
not know the QCparameters of this chip.
>
>
> I have found an instruction from C. Miller (one of the persons behind
simpleaffy) about how use the three functions provided by the
> simpleaffy package, or to make the needed .qcdf file:
> I need alpha values (that is okay) and I need control and spike
> probeIDs.
>
> I am using the Human Exon array 1.0 from affymetrix, and I do not know
what to fill in in the .qcdf file,
> anyone who knows how to get by this problem?
> Trying to get the probenames to set the values I ran into another problem..
>
> > prbs <- ls(cdfname)
> Error in as.environment(pos) :
> no item called "exon.pmcdf" on the search list
> >
>
> crashes like this shown here.
>
>
> Please if anyone knows or has an idea, basicly what I need is
> the .qcdf file for the HUman Exon array from Affy.
> Best regards
> Gard
>
> #################################
> Gard Thomassen
> Ph.D student CMBN, Rikshospitalet, Oslo
> Bioinformatician, Radiumhospitalet, Oslo
> Norway
> Email : gardt@...
> Office: + 47 22781736
> Phone +47 93674926

Friday, December 04, 2009

Quality control of Affymetrix arrays

I am playing around with different Bioconductor packages for QC on affy exon arrays.

Here is a nice introduction to quality assessment and processing.

http://www.bioconductor.org/workshops/2009/GenentechNov2009/Module2/module2-affy-preprocess.pdf


Here are some files one should have:

• CEL : contain one observation per spot
• CDF : map from spot locations to probeset and ultimately to the identity of the
gene being probed
• Bioconductor annotation" packages map from probe sets to gene and other
annotations.
• Tab-delimited, database, or other les provide phenotypic information.



Some packages are

arrayQualityMetrics
SimpleAffy
yaqcaffy
estrogen package vignette also has some QC. [>openVignette("estrogen")]

Before we start normnalization process here are some quality matric that Affymetrix advises

1)Average background : should be similar for all chips
2) Scale Factor: should be within 3 fold
3) # of genes called present : For similar samples - number should be similar. May
be different for different tissue types.
4) 3' to 5' ratio of GAPDH and beta-actin : should be close to one up to 3 is fine.
1.25 is what "simpleaffy" recommands.
5)Value for spike in transcripts: present in atleast 70% of arrays
please see
http://bioconductor.org/packages/2.5/bioc/vignettes/simpleaffy/inst/doc/QCandSimpleaffy.pdf

for more info.

======

We are interested in looking at two different aspects : Per slide aspects and Between slide aspects. Per slide aspects are - intensity dependence of ratios and spatial effects on the array. This can be done by looking at MA plots and a false image of chip. Between slide aspects are Homogeneity, outlier samples and biological meanings. This can be done by Boxplots, density plots, Heatmap and PCA. Other plots include Variance-mean dependency, GC content and probe mapping studies. Other Affy only plots include NUSE, RLE, RNA degradation, QC stats, PM/MM. Finally, one should be able to identify outliers.

The image function allows us to look at the spatial distribution of the intensities on a chip.

Another way to visualize what is going on on a chip is to look at the histogram of
its intensity distribution. Because of the large dynamical range (O(104)), it is useful to look at the log-transformed values

To compare the intensity distribution across several chips, we can look at the boxplots, both of the raw intensities and the normalized probe set values

The scatterplot is a visualization that is useful for assessing the variation (or
reproducibility, depending on how you look at it) between chips. We can look at all probes, the perfect match probes only, the mismatch probes only, and of course also at the normalized, probe-set-summarized data

Diff erences between arrays in the shape or center of the distribution often highlight the need for normalization.

The MA plot is a rotated version of a scatter plot. The
rotation helps to detect patterns as deviations from horizontal,
rather than diagonal.

• Instead of ploting two vectors Y2;j versus Y1;j , we plot
Mj = Y2;j - Y1;j versus Aj = (Y2;j + Y1;j)=2.
• if Y1 and Y2 are logarithmic expression values, then
{ Mj represents fold change for gene j
{ Aj represents average log intensity for gene j.

Thursday, November 19, 2009

Percents - GMAT Math Study Guide

This is taken from http://www.platinumgmat.com/gmat_study_guide/percents.

Percent Change vs. Percent Of

While most students find percentages to be an easier topic than one such as combinatorics, some individuals initially trip on the difference between a percent change and a percent of a number. Practically, this is the difference between saying "the price jumped 50%" and "the current price is 150% of the old price." Both of these phrases refer to the same amount, but are stated differently.
Percent Change

Percents are commonly used to measure or report the change in an amount. For example, a news reporter might say, "stocks rose 1.5% today" or a demographer might write, "minority representation in the population fell 3.5% during the past decade." The formula for calculating percent changes is:
percent change formula

This formula can also be expressed in decimal form. In other words, the following formula calculates the percent change between two numbers and represents this change in decimal form.
percent change formula as decimal

The following examples illustrate the use of this formula.
A company recently saw its stock fall from $10 to $9 as a result of a lawsuit award. What percent did the stock drop?
End Value = 9
Start Value = 10
Percent Change [as a percent] = ((9 - 10)/10) * 100 = -.1 * 100 = -10%

Another Example:
As a result of an increase in the required minimum wage and an increase in the price of raw materials, a manufacturer raised the price of its product from $50 to $60. By what percent did the manufacturer raise the price of its product?
End Value = 60
Start Value = 50
Percent Change [as a percent] = ((60 - 50)/50) * 100 = .2 * 100 = 20%

It is possible to calculate the percent change of a percent. Consider the following example:
Since the local government increased funding of high school education 10 years ago, the percent of students accepted at accredited four year universities jumped from 75% to 85%. By what percent did the percent of students accepted at four year universities increase over the 10 year period?
End Value = 85% = .85
Start Value = 75% = .75
Using Percents: Percent Change [as a percent] = ((85% - 75%)/75%) * 100 = 13.3% * 100 = 13.3%
Using Decimals: Percent Change [as a decimal] = ((.85 - .75)/.75) * 100 = .133
A Common Mistake in Working With Percent Decreases

Some students confuse a percent decrease of a certain percentage with finding the percent of a certain amount. The following example elucidates this confusion:
A foreign stock market index stood at 5,000 last year. However, since that time, its value fell 45%. What is the current value of the stock index?

Common Mistake: IndexToday = 5000(.45)
This calculation yields 45% of last year's index value. However, the question pertains to a 45% fall. Since the index's value fell 45%, its current value is 100% - 45% = 55% of last year's index value.
Correct Calculation: IndexToday = 5000(1-.45) = 5000(.55) = 2750
Percent of

Another common use of percents is as a measure of another number. For example, a stock analyst might say, "MicroMake's stock is trading at 130% of MacroMake's stock price." Similarly, a political historian might say, "President George W. Bush's approval rating in late November 2004 was about 50%, which is about 55% of his approval rating in late September 2001." In these instances, percents are being used not to describe change, but to compare amounts or quantities.

When working with percents that are used to compare different quantities, it is often best to translate each percent into decimals and set up equations or ratios. Consider the following examples:
What is 50% of 40?
Translate 50% into decimal format: 50% = .5
Translate the question into an equation: .5(40) = ?
.5(40) = 20

The following is a slightly more difficult example:
20 is what percent of 80?
Let X = the percent as a decimal
Translate the question into an equation: X(80) = 20
X = 20/80 = 1/4 = .25
Translate X into a percent: .25(100) = 25%

Percents can also be used to compare the size of percents. Consider the example with President George W. Bush's approval rating mentioned above.
President George W. Bush's approval rating in late November 2004 was about 50%, which is about 55% of his approval rating in late September 2001. What was President Bush's approval rating in late September 2001?
Let A = President Bush's approval rating in late September 2001
Condense Question Down to Simplify: 50% is 55% of A
Translate Into Equation: .50 = .55A
A [as a decimal] = .9
A [as a percent] = .9(100) = 90%

Recursive Percents

If a number rises by 30% and then falls by 35%, by what percent did it change from beginning to end? The topic of recursive (or successive) percents addresses this question. Consider an example:
From 2004 through 2007, the Dow Jones Industrials Average rose about 30%. However, during 2008, the Dow fell about 35%. About what percent did the Dow Jones change from 2004 through 2008?

Let DowBeginning of 2004 = X
DowEnd of 2007 = X(1 + 30%) = X(1.3)
DowEnd of 2008 = [X(1.3)](1-.35) = X(.845)

Percent Change = (End - Start/Start)*100
Percent Change = (X(.845) - X/X)*100 = -15.5%
Strategy: Picking Numbers (Especially 100)

Many students find it easier to solve problems involving percents by picking numbers instead of using theoretical variables. The previous question can be solved this way:
From 2004 through 2007, the Dow Jones Industrials Average rose about 30%. However, during 2008, the Dow fell about 35%. About what percent did the Dow Jones change from 2004 through 2008?

Let DowBeginning of 2004 = 100 [pick the number 100 instead of using a variable]
DowEnd of 2007 = 100(1.3)
DowEnd of 2008 = 100(1.3)(1-.35) = 84.5

The choice of 100 as a value for the Dow at the beginning of 2004 makes calculating the percent change from 2004 through 2008 much easier, as the next step should indicate.

Percent Change = (End - Start/Start)*100
Percent Change = (84.5 - 100/100)*100 = -15.5%
Interest Rate Problems

One rather common and important application of percents is the topic of interest rates and money. An important formula that relates interest, principal, and time follows:
Simple Interest Formula
I = PRT

I = Interest Payment
P = Principal
R = Interest Rate
T = Time Period
If a homeowner signs a 10 year loan for 5% worth $100,000, how much will his interest payment be the first year (assuming he pays interest once annually)?

T = 1 since the question asks for the interest, I, in the first year (i.e., a one year time period--not the entire 10 year time period)
P = $100,000
R = 5% = 0.05

I = $100,000(.05)(1) = $5000

While the above formula helps solve many problems, there are other problems that require another formula. The following formula is fundamental to the relationship between interest, time, present value, and future value:
FV = PV(1 + r)t
FV = Future Value = The amount of money to be received or owed at a future date t time periods from now
PV = Present Value = The amount of money to be received or owed at present (i.e., now)
r = Interest Rate = The interest rate on the money, expressed as a decimal
t = Time = The amount of time to pass between PV and FV

Note: The time period, t, and interest rate, r, must be expressed in the same terms. For example, one cannot use an annual interest rate and express time in terms of months. If you are using a value of t that expresses time in months, you must use a monthly interest rate. For more on this topic, see the compound interest section.

The following is an example of a common introductory interest rate problem.
If Sam invests $100,000 today and earned 5% a year, how much money would Sam have in 2 years?

PV = $100,000
r = 5% = 0.05
t = 2

FV = $100,000(1 + .05)2 = $110,250

Tuesday, October 06, 2009

Advances in Genetics is journal from Elsevier .. good for reviews.

Friday, August 07, 2009

simpler way to count the number of elements in a vector that are not NA

simpler way to count the number of elements in a vector that are not NA

sum( !is.na( yourvector ) )