[英]R: read_fwf () multiple text files from folder then write csv files to same folder (i.e., convert folder of text files to folder of csv files)
我想從空格分隔的文本文件的單個文件夾中讀取文件,然后將它們作為 csv 文件寫到同一文件夾中。
空格分隔的文本文件很煩人,第二行是破折號,每個文件末尾的三行帶有一些不正確的摘要值(見下文)。 這些被“read_fwf”中的“comment”和“skip”arguments 刪除。 如果有更好的方法來實現這一點,請指教。
Frame Clusters Total Area
-----------------------------
0 2 353
1 2 233
2 1 18
3 1 18
... ... ...
6230 1 38
6231 2 183
Total qualifying frame count = 6105
Total file cluster count = 42005
Total file biomass area = 8867980
我正在嘗試使用像 lapply 這樣的 tidyverse 選項而不是編碼循環。
我想我正在閱讀文本文件。 我的失敗似乎在 write.csv 部分代碼。
作為 R 的新用戶,我將非常感謝任何有關語法的建議或鏈接(即括號、縮進等)。 論壇帖子的清晰度提示也會有所幫助。 謝謝你。
# Clear all variables
rm(list = ls())
# Reference tidyverse
library(tidyverse)
# Create variable, "folder" for location of text files
folder <- "C:/Users/stai669/OneDrive - PNNL/Desktop/CRDC_P/DP/DIDSON snip
files/largeDataset/Cluster/Aft/N/"
# Create variable, "file_list" that lists all files in folder for "lapply" to loop through
filelist <- list.files(path = folder, pattern = "*.txt")
# Read in each file with "lapply"; other arguments for column names, etc.
data <- lapply(filelist, function(x) {
textfile <- read_fwf(
paste(folder, x, sep = ""),
fwf_positions(start = c(1, 6, 17), end = c(5, 16, 29),
comment = "T",
col_names = c("fram", "clust", "biom"),
skip = 2,
cols(fram = col_integer(), clust = col_integer(), biom = col_integer())
)
# Write the files to csv in the same folder
write.csv(textfile, file = sub(pattern = "\\.txt$", replacement = ".csv", x = x))
})
# Clear all variables
rm(list = ls())
# Reference tidyverse
library(tidyverse)
# Create variable, "file_list" that lists all files in folder for "lapply()" to loop through
filelist <- list.files(pattern = "*.txt")
# Read in each file with "lapply"; other arguments for column names, etc.
data <- lapply(filelist, function(x) {
textfile <- read_fwf(
paste(x, sep = ""),
fwf_positions(start = c(1, 6, 17), end = c(5, 16, 29), col_names = c("fram", "clust", "biom")),
comment = "T",
skip = 2,
cols(fram = col_integer(), clust = col_integer(), biom = col_integer())
)
# Write the files as csv to the same folder
write.csv(textfile, file = sub(pattern = "\\.txt$", replacement = ".csv", x = x))
})
同樣,請注意“col_names”參數與“fwf_positions”一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.