r - 考虑文件名加入不同文件夹中的数据
问题描述
大家早上好,我有一个问题,我在搜索中没有找到任何东西。好吧,我有两个文件夹,每个文件夹都有 121 个文件 (.txt),其中包含子盆地的温度数据(一个具有最高温度,一个具有最低温度)。数据具有相同的名称和相同的行数 (13654)。
我想按名称加入这些数据,以便文件具有以逗号分隔的 tmp min 和 tmp max 数据。
我想提前道歉,因为我没有附上一个可重现的例子,所以我附上了带有图案的屏幕和部分原始数据以供下载。
下载链接https://drive.google.com/file/d/1DdE1eWK0xf9XBRdocI-bN1flxDRggLVv/view?usp=sharing 谢谢
解决方案
这是一种 data.table 方法。
baseDir <- "~/ex/ex1/data_T/"
setwd(baseDir)
library(data.table)
files <- list.files(recursive=TRUE, pattern = "*.txt")
DT <- rbindlist(lapply(setNames(as.list(files), files), fread), idcol = "file")
DT[, `:=` (MinMax = factor(grepl("max", file), labels = c("min", "max")),
p = as.numeric(gsub("(.*/p)([0-9]+)(.txt)", "\\2", file)))]
DT[, idx := 1:.N, by=list(p, MinMax)]
setkeyv(DT, c("p", "idx"))
DT <- dcast(DT[, -"file"], p + idx ~ MinMax, value.var="V1", fun.aggregate = NULL)
DT
#> p idx min max
#> 1: 1 1 19800101.0 19800101.0
#> 2: 1 2 23.2 34.1
#> 3: 1 3 24.0 32.6
#> 4: 1 4 23.3 34.1
#> 5: 1 5 23.8 34.6
#> ---
#> 216252: 16 13512 24.0 36.5
#> 216253: 16 13513 22.6 34.5
#> 216254: 16 13514 22.1 35.1
#> 216255: 16 13515 22.1 35.9
#> 216256: 16 13516 22.7 36.4
head(DT[, .(min, max)])
#> min max
#> 1: 19800101.0 19800101.0
#> 2: 23.2 34.1
#> 3: 24.0 32.6
#> 4: 23.3 34.1
#> 5: 23.8 34.6
#> 6: 23.2 33.9
## now you can save csv files
fwrite(DT[, .(min, max)], file = "MinMax.csv", col.names = FALSE)
## or write them out into separate files:
outfiles <- split(DT, DT$p)
lapply(seq_along(outfiles), function(x) fwrite(outfiles[[x]][, .(min, max)], file = paste0("MinMax_p", x, ".csv"), col.names = FALSE ))
由reprex 包(v0.3.0)于 2020-03-26 创建
推荐阅读
- java - Java Process Builder 运行本地安装的程序
- python - 正则表达式在 python 中没有给出正确的结果
- python - 用于发送内联图像或 excel 的 Python 函数
- reactjs - 我可以在删除后立即插入 reportWebVitals 和 App.test.js 吗?
- encryption - 3DES-Sweet32 漏洞补偿控制?
- python - 根据位数查找所有数字组合
- python - 在 Tkinter 中下载文件时权限被拒绝
- r - 将工作表名称作为变量添加到我的数据框
- .net - .NET MVC 应用程序的 Office365 身份验证
- java - 将 Guava Sets 转换为 List 的最快方法