簡體   English   中英

對目錄中的文件列表進行多次操作,然后將新的動態文件名保存到R,Lapply?

[英]Iterate several operations over a list of files in a directory and save with new dynamic filename in R, Lapply?

我是R的新手,我想將文件列表作為單獨的數據幀讀取,對每個文件執行幾個操作,然后將它們另存為具有動態文件名的單獨文件。 我以為我應該用棉布,但不確定。

這是我編寫的適用於一個文件的代碼:

df <- read.fwf('USC00011084.dly', widths = c(21, rep(c(5, 1, 1, 1),31)))

df2 <- df[-c(3:5, 7:9, 11:13, 15:17, 19:21, 23:25, 27:29, 31:33, 35:37, 39:41, 43:45, 47:49, 51:53, 55:57, 59:61, 63:65, 67:69, 71:73, 75:77, 79:81, 83:85, 87:89, 91:93, 95:97, 99:101, 103:105, 107:109, 111:113, 115:117, 119:121, 123:125)] 

df2[df2=="-9999"]<-NA

df$new <- rowSums(df2[,2:32], na.rm = TRUE)

df2["Total"] <- df$new

colnames(df2) <- c("StationDateType", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "28", "30", "31", "TotalMonthly")

Prcp <- df2[grep("PRCP", df2$StationDateType),]

write.table(Prcp, "USC00011084Prcp.txt", sep="\t", row.names=FALSE)

如何為目錄中的文件列表執行此操作? 有任何想法嗎? 謝謝。

您可以嘗試一下...您可以獲得文件列表:

files <- list.files(getwd())

編寫一個函數,執行所需的分析,然后將結果寫到表中。 在這里,我們使用tools :: file_path_sans_ext提取文件名(不帶文件擴展名),最后使用它來命名要保存為txt的表。

myFunction <- function(files){
  fileName <- tools::file_path_sans_ext(files)
  df <- read.fwf(files, widths = c(21, rep(c(5, 1, 1, 1),31)))
  # rest of your code
  # ...
  write.table(Prcp, paste0(fileName, "Prcp.txt"), sep="\t", row.names=FALSE)
}

您可以使用lapply對文件中的每個文件運行功能。

lapply(files, function(x) myFunction(x))

暫無
暫無

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

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