Home > database >  Read and rename columns of multiple files with purr in R
Read and rename columns of multiple files with purr in R

Time:10-23

I have multiple files that have the same structure. I want to be able to read all these files simultaneously with the fread and then dplyr::rename them at the same time.

I want to achieve something like this

files=c(file1.txt,file2.txt,file3.txt)

files |> 
map(fread, rename(test=1,check=2)

But, of course, it is wrong. Any help or guidance to understand the logic of reading and renaming in purr is appreciated.

It's hard to create a fully reproducible example because of the need of a directory and txt files.

CodePudding user response:

You could achieve your desired result by piping the imported data into rename:

library(purrr)
library(data.table)
library(dplyr)

files <- paste0("file", 1:3, ".txt") 

## Create example files in a temp dir
temp <- tempdir()

walk(files, ~ write.csv(iris[1:2], file.path(temp, .x), row.names = FALSE))

files |> 
  map(~ fread(file.path(temp, .x)) %>% rename(test = 1, check = 2))
#> [[1]]
#>      test check
#>   1:  5.1   3.5
#>   2:  4.9   3.0
#>   3:  4.7   3.2
#>   4:  4.6   3.1
#>   5:  5.0   3.6
#>  ---           
#> 146:  6.7   3.0
#> 147:  6.3   2.5
#> 148:  6.5   3.0
#> 149:  6.2   3.4
#> 150:  5.9   3.0
#> 
#> [[2]]
#>      test check
#>   1:  5.1   3.5
#>   2:  4.9   3.0
#>   3:  4.7   3.2
#>   4:  4.6   3.1
#>   5:  5.0   3.6
#>  ---           
#> 146:  6.7   3.0
#> 147:  6.3   2.5
#> 148:  6.5   3.0
#> 149:  6.2   3.4
#> 150:  5.9   3.0
#> 
#> [[3]]
#>      test check
#>   1:  5.1   3.5
#>   2:  4.9   3.0
#>   3:  4.7   3.2
#>   4:  4.6   3.1
#>   5:  5.0   3.6
#>  ---           
#> 146:  6.7   3.0
#> 147:  6.3   2.5
#> 148:  6.5   3.0
#> 149:  6.2   3.4
#> 150:  5.9   3.0
  • Related