0

I am looping a number of csv files in a folder using the map function. I want to save the results of the loop using a sliced version of the name of the csv. But I am getting an error when attempting to save the results to csv. Here is my code

library(tidyverse)
library(fs)
library(dismo)

file_paths <- fs::dir_ls("loop/")

file_paths %>%
  map(function (path){
    all_data <- read_csv(path, show_col_types = FALSE)
    name <- tools::file_path_sans_ext(basename(file_paths))
    print(name)
    t_max <- all_data[,c(2)]
    t_min <- all_data[, c(3)]
    rain_fall <- all_data[,c(4)]
    res <- data.frame(biovars(t_max, t_min, rain_fall))
    myfile = sprintf("%s_bio.csv", name)
    write_csv(res, file=myfile, col_names = TRUE)
  })

Error:

Error in if (is_url(path)) { : the condition has length > 1
2
  • 3
    If you have errors then please include the literal error, don't make us guess. My guess: replace tools::file_path_sans_ext(basename(file_paths)) with tools::file_path_sans_ext(basename(path)). Commented Nov 28, 2022 at 8:57
  • 1
    @r2evans, I have updated the question to include the error. How do I vote for your answer? Because it has actually solved the problem. Commented Nov 28, 2022 at 13:12

1 Answer 1

0

You're using the full vector of full_paths inside your map, you should be using just the singular path:

file_paths %>%
  map(function (path){
    all_data <- read_csv(path, show_col_types = FALSE)
    name <- tools::file_path_sans_ext(basename(path))
    print(name)
    t_max <- all_data[,c(2)]
    t_min <- all_data[, c(3)]
    rain_fall <- all_data[,c(4)]
    res <- data.frame(biovars(t_max, t_min, rain_fall))
    myfile = sprintf("%s_bio.csv", name)
    write_csv(res, file=myfile, col_names = TRUE)
  })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.