簡體   English   中英

R - 在 for 循環中打印 object 的名稱

[英]R - print name of object in a for loop

我正在使用 R 中的 for 循環將一些代碼應用於許多文件。 我想在每次循環迭代后保存一個 output 文件,根據循環迭代中正在處理的文件命名。 如何打印每輪循環中使用的文件的名稱?

我對 for 循環的理解是,您向它提供一個list和一些code ,然后它會遍歷list的每個項目並將code應用於它。 所以在我看來,我應該能夠在循環的每一輪中提取list正在使用的項目的名稱。 如果這是錯誤的,請糾正我。

經過大量搜索,這是我能夠得到的最接近的:

# load lines files
csv1 <- read.csv("csv1.csv")
csv2 <- read.csv("csv2.csv")

# make list of lines files
object.list <- list(csv1, csv2)

for(i in object.list){
  print(deparse(substitute(i)))
}

產生:

[1] "i"
[1] "i"

但我希望它產生:

[1] "csv1"
[1] "csv2"

有任何想法嗎? 請舉個簡單的例子。

如何命名列表的元素:

# load lines files
csv1 <- "file content"
csv2 <- "some other file content"

# make list of lines files
object.list <- list(csv1 = csv1, csv2 = csv2)

for(name in names(object.list)){
  print(name)
  print(object.list[[name]])
}

我不相信有直接的方法可以做到這一點。 R 不記得i是使用csv1csv2創建的。 它只知道值。 也許這種解決方法對您有用:

object.list <- list(csv1, csv2)
names(object.list) <- c( substitute(csv1), substitute(csv2))

for(i in 1:length(object.list){
  print(names(object.list[i]))
}

添加原始變量作為名稱,您可以稍后訪問它們。

更改工作流程可能會為您提供更好的服務...這是使用我放置的一些 csv 文件的示例

# You could also do this via a system call
# No need for a list a vector will do
files_to_read <- c("bfwicox.csv", "churn.csv")
# Name automatically
names(files_to_read) <- files_to_read

# Now run loop
for(name in names(files_to_read)){
  data <- read.csv(files_to_read[[name]])
  print(paste("This is a summary of the first two variables in file...", 
              files_to_read[[name]]))
  print(summary(data[1:2]))
}

[1] "This is a summary of the first two variables in file... bfwicox.csv"
       X             income      
 Min.   :    1   Min.   :  1100  
 1st Qu.: 4250   1st Qu.: 25000  
 Median : 8500   Median : 40000  
 Mean   : 8500   Mean   : 50687  
 3rd Qu.:12750   3rd Qu.: 65000  
 Max.   :16999   Max.   :250000  
[1] "This is a summary of the first two variables in file... churn.csv"
      ID               ACLENGTH    
 Length:5000        Min.   :  0.0  
 Class :character   1st Qu.: 73.0  
 Mode  :character   Median :100.0  
                    Mean   :100.9  
                    3rd Qu.:127.0  
                    Max.   :227.0  

暫無
暫無

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

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