Read multiple csv within a function without a for loop

I am trying to read multiple .csv files but within a function with a single input variable, so I can modify each file with the same of lines of code. All my files (All_0320, Part_0320, etc.) are located in the same folder.

func1 <- function(file){
   setwd("C:/Users/Myname/FolderWithData/")
   z1 <- read.csv(paste0(file,".csv",sep=""))
#lines of code that modify z1 
 return(z1)
}

num1 <- func1(All_0320)
num2 <- func1(Part_0320)

This gives me an error " Error in file(file, "rt") : invalid 'description' argument "

What am I doing wrong?
I used the code from here as an example: Doing Macros in R

Your error is that you are entering func1(All_0320) instead of func1("All_0320").

library(tidyverse)

load_csv_file <- function(file_name) {
  
  address <- "C:/Users/Myname/FolderWithData/"
  
  read_csv(paste0(address, file_name)) %>%
    mutate(new_col = sum(old_col))
}

my_data <- load_csv_file("banana prices.csv")

Thank you so much, that was it! I was trying to use the names of the files "All_0320" for a column in the output result but might not be able to do that with the quotes around them.. but that's ok.

I've commented out the CSV portion so that you can run this on your machine and see how it works for yourself. Just replace df %>% with the commented out line and you're good to go.


df <- data.table(a = 1:10)

load_csv_file <- function(file_name, col_name) {
  
  address <- "C:/Users/Myname/FolderWithData/"
  
  # read_csv(paste0(address, file_name)) %>%
  
  df %>% 
    mutate("{col_name}" := sum(a))
}

load_csv_file("banana prices.csv", "new_column_name")

Thanks again @ZykeZero. But the df %>%
# mutate(col_name = sum(a))
mutate("{col_name}" := sum(a)) part is not doing anything on my end...

mine looks like this:

df %>% 
mutate ("{col_name}" := value )

value is the name of the original column.

Nevermind, I had a small typo and now it's fixed and working. Appreciate your help so much!

"{col_name}" is the location in the function that R will replace with what you pass to col_name in the function.

function(file_name, col_name)

you have to look at the whole piece that I had provided. I created a dataframe with the column a and values 1:10
df <- data.table(a = 1:10)

and then created the function.

And then used the function so that you could see in the output that "new_column_name" was the name of the new column created.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.