R:read_fwf()从文件夹中读取多个文本文件,然后将csv文件写入同一文件夹(即,将文本文件的文件夹转换为csv文



从一个由空格分隔的文本文件组成的文件夹中,我想读取文件,然后将它们作为csv文件写入同一文件夹。

空格分隔的文本文件很烦人,第二行是破折号,每个文件末尾的三行有一些不正确的摘要值(见下文(。用";评论";以及";跳过";";read_fwf";。如果有更好的方法来实现这一点,请提供建议。

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";。

相关内容

  • 没有找到相关文章

最新更新