簡體   English   中英

(Pearson 的)數據框的相關循環

[英](Pearson's) Correlation loop through the data frame

我有一個包含 159 個 obs 和 27 個變量的數據框,我想將第 4 列(變量 4)中的所有 159 個 obs 與以下每一列(變量)相關聯,這是將第 4 列與 5 相關聯,然后是第 4 列與 6 等等......我一直沒有成功地嘗試創建一個循環,而且由於我是 R 的初學者,結果比我想象的要難。 我想讓它變得更簡單的原因是我需要對更多的數據幀做同樣的事情,如果我有一個可以做到這一點的函數,它會更容易,更省時。 因此,如果有人可以幫助我,那就太好了。

 df <- ZEB1_23genes # CHANGE ZEB1_23genes for df (dataframe)

  for (i in colnames(df)){      # Check the class of the variables
         print(class(df[[i]]))
  }

print(df)

# Correlate ZEB1 with each of the 23 genes accordingly to Pearson's method


cor.test(df$ZEB1, df$PITPNC1, method = "pearson")
### OR ###
cor.test(df[,4], df[,5])

所以我可以單獨關聯,但我不能創建一個循環來返回到第 4 列並將其關聯到下一列(5、6、...、27)。

謝謝!

如果我正確理解了您的問題,那么下面的解決方案應該可以很好地工作。

#Sample data
df <- data.frame(matrix(data = sample(runif(100000), 4293), nrow = 159, ncol = 27))

#Correlation function
#Takes data.frame contains columns with values to be correlated as input
#The column against which other columns must be correlated cab be specified (start_col; default is 4)
#The number of columns to be correlated against start_col can also be specified (end_col; default is all columns after start_col)
#Function returns a data.frame containing start_col, end_col, and correlation value as rows.

my_correlator <- function(mydf, start_col = 4, end_col = 0){
    if(end_col == 0){
    end_col <- ncol(mydf)
  }
  #out_corr_df <- data.frame(start_col = c(), end_col = c(), corr_val = c())
  out_corr <- list()
  for(i in (start_col+1):end_col){
    out_corr[[i]] <- data.frame(start_col = start_col, end_col = i, corr_val = as.numeric(cor.test(mydf[, start_col], mydf[, i])$estimate))
  }
  return(do.call("rbind", out_corr))
}

test_run <- my_correlator(df, 4)

head(test_run)

#   start_col end_col     corr_val
# 1         4       5 -0.027508521
# 2         4       6  0.100414199
# 3         4       7  0.036648608
# 4         4       8 -0.050845418
# 5         4       9 -0.003625019
# 6         4      10 -0.058172227

該函數基本上將一個data.frame作為輸入並吐出(作為輸出)另一個data.frame其中包含來自原始data.frame的給定列與所有后續列之間的相關性。 我不知道您的數據的結構,顯然,如果遇到意外情況(例如,其中一列中的一列字符),此函數將失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM