2012-09-21 8 views
5

Iは、各遺伝子名を繰り返し、2つの条件の値が含まれているdata.frame有する:は、データフレーム内の連続した行のペアbetwen差を計算 - R

df <- data.frame(gene=c("A","A","B","B","C","C"), 
condition=c("control","treatment","control","treatment","control","treatment"), 
count=c(10, 2, 5, 8, 5, 1), 
sd=c(1, 0.2, 0.1, 2, 0.8, 0.1)) 

    gene condition count sd 
1 A control 10 1.0 
2 A treatment  2 0.2 
3 B control  5 0.1 
4 B treatment  8 2.0 
5 C control  5 0.8 
6 C treatment  1 0.1 

をIがあれば計算します治療後の「カウント」の増減であり、そのようにマークしたりサブセットしたりする。それは、(擬似コード)である:

for each unique(gene) do 
    if df[geneRow1,3]-df[geneRow2,3] > 0 then gene is "up" 
     else gene is "down" 

それが最終的にどのように見えるか、この(最後の列はオプションです):

up-regulated 
gene condition count sd regulation 
B control  5 0.1 up 
B treatment 8 2.0 up 

down-regulated 
gene condition count sd regulation 
A control  10 1.0 down 
A treatment 2 0.2 down 
C control  5 0.8 down 
C treatment 1 0.1 down 

私は一緒に遊ん含め、これで私の脳をかき集めてきました私は解決策を見つけることに失敗しました - 不運な生物学者にしてください。

乾杯。

答えて

5

plyr解決策のようなものになります。

library(plyr) 
reg.fun <- function(x) { 
    reg.diff <- x$count[x$condition=='control'] - x$count[x$condition=='treatment'] 
    x$regulation <- ifelse(reg.diff > 0, 'up', 'down') 

    x 
} 

ddply(df, .(gene), reg.fun) 


    gene condition count sd regulation 
1 A control 10 1.0   up 
2 A treatment  2 0.2   up 
3 B control  5 0.1  down 
4 B treatment  8 2.0  down 
5 C control  5 0.8   up 
6 C treatment  1 0.1   up 
> 

をまたおよび/または異なる形状のデータと異なるパッケージでこれをやって考えることもできます。このような

df.w <- reshape(df, direction='wide', idvar='gene', timevar='condition') 

library(data.table) 
DT <- data.table(df.w, key='gene') 

DT[, regulation:=ifelse(count.control-count.treatment > 0, 'up', 'down'), by=gene] 

    gene count.control sd.control count.treatment sd.treatment regulation 
1: A   10  1.0    2   0.2   up 
2: B    5  0.1    8   2.0  down 
3: C    5  0.8    1   0.1   up 
>  
+0

素晴らしい、それは働いた!私はddplyが答えの一部であるかもしれないと感じましたが、私はreg.funを考え出すことはないと思います。乾杯。 – fridaymeetssunday

+0

@krespimそして、plyrとdata.tableを比較する行のペアをグループ化する[ベンチマーク](http://stackoverflow.com/revisions/11463757/3)があります。 –

3

何かを:

df$up.down <- with(df, ave(count, gene, 
       FUN=function(diffs) c("up", "down")[1+(diff(diffs) < 0) ])) 
spltdf <- split(df, df$up.down) 

> df 
    gene condition count sd up.down 
1 A control 10 1.0 down 
2 A treatment  2 0.2 down 
3 B control  5 0.1  up 
4 B treatment  8 2.0  up 
5 C control  5 0.8 down 
6 C treatment  1 0.1 down 
> spltdf 
$down 
    gene condition count sd up.down 
1 A control 10 1.0 down 
2 A treatment  2 0.2 down 
5 C control  5 0.8 down 
6 C treatment  1 0.1 down 

$up 
    gene condition count sd up.down 
3 B control  5 0.1  up 
4 B treatment  8 2.0  up 
関連する問題