2013-11-27 39 views
1

條件在不同列中選擇行我有以下數據如何基於R中

Probe dumhead1 cond1 cond2 cond3 
foo dum1  1.5 3.2 3.0 
bar dum10 2.0 1.0 2.1 
qux dum22 0.4 2.3 2.2 

我想要做的就是爲每個cond 1 ..3 報告其中值大於2.0探頭。

實際上,探針的數量約爲20k。

把所得本(由手工完成):

> cond1 
[1] "bar" 
> cond2 
[1] "foo" "qux" 
> cond3 
[1] "foo" "bar" "qux" 

什麼是做到這一點的呢? 我被這個代碼卡住了.... 完成for循環的方式非常慢。

dat <- read.table("http://dpaste.com/1484534/plain/",sep=" ",header="TRUE") 
nofprobe <- nrow(dat) 
#...to be added.... 

回答

2

使用apply(),使更多的擴展:

apply(dat[,3:5],2,FUN=function(x)dat$Probe[x>=2]) 

# breaking down the function call: 
apply(dat[,3:5],      # the subset of columns to test 
     2,        # 2 means run apply() col-wise 
     FUN=function(x)dat$Probe[x>=2]) # dat$Probe gives the levels 
             # returns rows where val >=2 
             # for each column (passed by x) 

編輯更新爲使用ddply()從` plyr'包來設定個別條件:

require(plyr) 

    results<-ddply(dat,.(Probe),summarize, 
      cond1=(cond1>=2), 
      cond2=(cond2<2), 
      cond3=(cond3>=0) 
     ) 

    apply(results[,2:4],2,FUN=function(x)dat$Probe[x]) # this returns same format 
+1

我比我更喜歡這個答案,因爲它涉及的輸入較少,特別是如果您正在查看的值> 2的列數很大。 – Jota

+0

謝謝。很好的答案!後來我如何訪問每列的向量(最好在for-loop上下文中)。稍後爲每個列(條件)我想執行一個操作。 – neversaint

+0

Hi @neversaint已更新,以顯示如何使用ddply爲每行1個條件返回測試向量,然後轉換爲相同的返回格式。 – Troy

1

如果只有3 COND列,那麼這似乎是合理的:

dat[dat$cond1 > 2, ]$Probe 
dat[dat$cond2 > 2, ]$Probe 
dat[dat$cond3 > 2, ]$Probe