簡體   English   中英

R 中的導入循環(read.csv)

[英]Import-loop in R (read.csv)

我嘗試導入名稱中間帶有持續數字的 *.csv 文件 - 所以我嘗試使用 for 循環來生成數字並將其粘貼到文件名中:

for (Number in 20:30){
  (paste("Test.",Number,"File"))<- read.csv("~/Test.-",Number,"File".csv", sep=";", comment.char="#")

}

如何避免空白,以便導入有效? 還有其他建議嗎? 非常感謝!

您可以向paste()添加額外的參數

for (Number in 20:30){
  name <- paste("Test.",Number,"File.csv", sep = "")
  name <- read.csv(name, sep=";", comment.char="#")

}

sep=""將刪除名稱中的空格。

@manaR 的 Anwer 解決了空白的問題。 stringr包 str_c 也允許您這樣做。 您可以使用assign在用戶環境中創建一個具有正確名稱的新變量。

require(stringr)
for (Number in 20:30){
        file<- read.csv(str_c("~/Test.-",Number,"File",".csv"), sep=";",comment.char="#")
        # assign value to the variable name x 
        assign(x=str_c("Test.",Number,"File"),value=file,envir=.GlobalEnv)  
      }



   # this example with the winprogressbar only works under windows
    # it allows you to load all the files with extension .csv in one directory


    datawd<-"c:/path/to/mydirectory/"
    listoffiles<-list.files(datawd) # list of files
    # find out which files have extensions csv
    listoffiles<-listoffiles[grep(".csv",listoffiles)]
    # creating the full path
    mypaths<-str_c(datawd,listoffiles)
    progress<-utils::winProgressBar(title = "loading csv files",
            label = "progression %",
            min = 0,
            max = length(mypaths), 
            initial = 0,
            width = 400)
    for (i in 1:length(mypaths)){
        utils::setWinProgressBar(progress,i,label=listoffiles[i])       
        file<- read.csv(mypaths, sep=";",comment.char="#")
        # assign value to the variable name x 
        assign(x=str_c("Test.",Number,"File"),value=file,envir=.GlobalEnv)  
    }

試試這個:

for (number in 20:30){
    name<-paste("Test.-",number,"File",sep="")
    name<-read.csv(paste(filename,".csv",sep=""))
   }

默認情況下,如果您未在 paste() 中指定 sep="",則 sep 將設置為 " "。 但仍然在最后一列中,您會得到一個“;” 您必須使用 gsub 函數替換它。

sep=","使用"," sep=","幫助了我。 感謝 manaR,塞德里克。

for (i in 1:96){
  d <- read.csv(str_c("GRID_",Number,".csv"), sep=",",comment.char="#")
  source("Function_for grid.R")
}

暫無
暫無

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

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