2012-09-21 2 views
5

를 I 각 유전자 이름이 반복 및 2 개의 조건에 대한 값을 포함시킨 data.frame있다 : I가 있으면 계산할데이터 프레임의 연속 행 쌍 타협 차이를 계산 - 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 

이 치료 후 "카운트 (count)"의 증가 또는 감소이며이를 치료 및/또는 부분 집합으로 표시합니다. (마지막 열은 선택 사항입니다)이 결국 어떻게 보일지

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 

나는 함께 연주를 포함하여,이 내 머리를 긁어 모아왔다 ddply, 나는 해결책을 찾지 못했습니다. - 불행한 생물 학자 바랍니다.

건배.

답변

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을 비교하는 행 쌍을 그룹화하는 [benchmark] (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 
관련 문제