簡體   English   中英

通過 R For 循環創建數據幀

[英]Creating Dataframes through R For Loop

對 R 相當陌生,因此感謝任何指導。

目標:我試圖在一個簡短的腳本中創建數百個數據幀。 它們遵循一種模式,所以我認為 For 循環就足夠了,但是data.frame函數似乎忽略了變量的變量性質,在它出現時讀取它。 下面是一個例子:

# Defining some dummy variables for the sake of this example
dfTitles <- c("C2000.AMY", "C2000.ACC", "C2001.AMY", "C2001.ACC") 
Copes <- c("Cope1", "Cope2", "Cope3", "Cope4")
Voxels <- c(1:338)

# (Theoretically) creating a separate dataframe for each of the terms in 'dfTitles'   
for (i in dfTitles){
 i <- data.frame(matrix(0, nrow = 4, ncol = 338, dimnames = list(Copes, Voxels)))
}

# Trying an alternative method
for (i in 1:length(dfTitles))
 {dfTitles[i] <- data.frame(matrix(0, nrow = 4, ncol = 338, dimnames = list(Copes, Voxels)))}

這導致創建一個名為“i”的數據幀,在前者中,或在后者的情況下創建一個 4 的列表。 有任何想法嗎? 謝謝!


可能不必要的背景信息:我們正在使用 fMRI 數據進行分析,該分析將在刺激、大腦體素、大腦區域和參與者之間運行相關性。 我們正在關聯整個矩陣,因此通過參與者 ID 和大腦區域將值(又名 COPE)分成單獨的數據幀將使下一步變得更加容易。 在將數據加載並分類到一個大數據幀中后,我已經嘗試了下一步,這是一個很大的痛苦。

在 for 循環中創建對象時,它們需要在循環的下一次迭代之前保存在某處,否則它會被覆蓋。

一種處理方法是在循環開始之前使用c()創建一個空list或向量,並附加循環每次運行的輸出。

處理它的另一種方法是在繼續循環的下一次迭代之前將對象分配給您的環境。

# Defining some dummy variables for the sake of this example
dfTitles <- c("C2000.AMY", "C2000.ACC", "C2001.AMY", "C2001.ACC") 
Copes <- c("Cope1", "Cope2", "Cope3", "Cope4")
Voxels <- c(1:338)

# initialize a list to store the data.frame output
df_list <- list()
for (d in dfTitles) {
  # create data.frame with the dfTitle, and 1 row per Copes observation
  df <- data.frame(dfTitle = d,
                   Copes = Copes)
  # append columns for Voxels
  # setting to NA, can be reassigned later as needed
  for (v in Voxels) {
    df[[paste0("Voxel", v)]] <- NA
  }
  # store df in the list as the 'd'th element
  df_list[[d]] <- df
  # or, assign the object to your environment
  # assign(d, df)
}
# data.frames can be referenced by name
names(df_list)
head(df_list$C2000.AMY)
rm(list=ls)
dfTitles <- c("C2000.AMY", "C2000.ACC", "C2001.AMY", "C2001.ACC") 
Copes <- c("Cope1", "Cope2", "Cope3", "Cope4")
Voxels <- c(1:3)

# (Theoretically) creating a separate dataframe for each of the terms in 'dfTitles'   
nr <- length(Voxels)
nc <- length(Copes)
N <- length(dfTitles) # Number of data frames, same as length of dfTitles

DF <- vector(N, mode="list")

for (i in 1:N){
  DF[[i]] <- data.frame(matrix(rnorm(nr*nc), nrow = nr))
  dimnames(DF[[i]]) <- list(Voxels, Copes)
}

names(DF) <- dfTitles
DF[1:2]

$C2000.AMY
       Cope1     Cope2      Cope3      Cope4
1 -0.8293164 -1.813807 -0.3290645 -0.7730110
2 -1.1965588  1.022871 -0.7764960 -0.3056280
3  0.2536782 -0.365232  2.3949076  0.5672671

$C2000.ACC
       Cope1    Cope2      Cope3      Cope4
1 -0.7505513 1.023325 -0.3110537 -1.4298174
2  1.2807725 1.216997  1.0644983  1.6374749
3  1.0047408 1.385460  0.1527678  0.1576037

暫無
暫無

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

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