2017-04-14 27 views
3

我是新來的R和我有RNA測序結果的25個樣品。我想應用相同的函數來計算我的目標基因(如基因ABC)與所有25個樣本的相關性。應用到多個數據集相同功能中的R

我知道如何單獨做到這一點。這裏是我的代碼做到這一點:

df <- read.table("Sample1.txt", header=T, sep="\t") 

# gene expression values of interest 
gene <-as.numeric(df["ABC",]) 

# correlate gene with all others genes in the expression set 
correlations <- apply(df,1,function(x){cor(gene,x)}) 

但現在我有他們25。我用樂器一次讀完。

data <- c("Sample1.txt", "Sample2.txt",..."Sample25.txt") 
df <- lapply(data, read.table) 
names(df) <- data 

但是,我失去了如何將它與我上面的其他代碼連接起來計算基因相關性。我已經閱讀了一些相關的主題,但仍然無法弄清楚。任何人都可以幫我嗎?謝謝!

+0

這將有助於瞭解你的輸入和輸出看起來像在這裏,作爲答案實際上取決於事情如何格式化。 – caw5cv

+3

總結你的第一塊塊的,需要一個文件名,並返回'correlations'功能。然後,做'lapply(數據,yourFunction中)' –

+0

@Marat,你能請提供一個答案?對不起,我對語言理解有點新。 – kin182

回答

2

你應該這樣做:

files <- c("Sample1.txt", "Sample2.txt", ..., "Sample25.txt") 

myfunc <- function(file) { 
    df <- read.table(file, header=TRUE, sep="\t") 

    # gene expression values of interest 
    gene <- as.numeric(df["ABC",]) 

    # correlate gene with all others genes in the expression set 
    correlations <- apply(df, 1, function(x) cor(gene, x)) 
} 

lapply(files, myfunc) 

那就是我爲您推薦的風格。這是我的風格會做:

myfunc <- function(file) { 
    df <- read.table(file, header=TRUE, sep="\t") 
    gene <- as.numeric(df["ABC",]) # gene expression values of interest 
    apply(df, 1, FUN=cor, y=gene) # correlate gene with all others 
} 

files <- c("Sample1.txt", "Sample2.txt", ..., "Sample25.txt") 
lapply(files, myfunc) 

也許你想要保存結果的對象:

L <- lapply(files, myfunc) 

對於功能甚至可以做(因爲cor()採用矩陣參數)):

myfunc <- function(file) { 
    df <- read.table(file, header=TRUE, sep="\t") 
    cor(t(df), y=as.numeric(df["ABC",])) # correlate gene with all others 
} 
+0

我在match.fun(FUN)的錯誤'錯誤:參數「FUN」缺失,沒有default'。但是,我不知道這意味着什麼。 – kin182

+0

什麼源代碼行給出了該錯誤? – jogo

+0

@ jogo的答案正是我所要做的,只是不要忘記將生成的列表保存在一個變量中(例如'L < - lapply(files,myfunc)')。錯誤消息可能來自應用程序或lapply,但答案中的語法似乎是正確的。 –