考虑文件名将数据加入不同的文件夹中

问题描述 投票:0回答:1

大家早上好,我有一个问题,我没有在搜索中找到任何东西。好吧,我有两个文件夹,每个文件夹包含121个文件(.txt),其中包含子盆地的温度数据(一个具有最高温度,一个具有最低温度)。数据具有相同的名称和相同的行数(13654)。folder structuredata structure

我想按名称将这些数据连接起来,这样文件中的tmp min和tmp max数据之间就用逗号分隔。

new data struture

我想为此致歉,因为没有在上面附加可复制的示例,所以我在屏幕上附加了图案以及部分原始数据以供下载。

下载链接https://drive.google.com/file/d/1DdE1eWK0xf9XBRdocI-bN1flxDRggLVv/view?usp=sharing谢谢

r
1个回答
0
投票

这是一个数据表方法。

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 package(v0.3.0)在2020-03-26创建

© www.soinside.com 2019 - 2024. All rights reserved.