Reading CSV files

Hello,

Could anyone please help me with the code to read multiple csv files using a for loop in R

Thank you

Something like this could help you.

Remember set the work directory, and put all files in the same folder.

library(tidyverse)
DF <-  list.files(path = "Your_path", 
                              pattern = "*.csv") %>% 
       map_df(~read_csv(.))
DF

Thanks for the reply, but I would like to import all the csv files using for loop any code using loop would be helpful for me

Ok, for this check this example.

You don't need a Loop for that, R works better using vectorized functions rather than loops. Can you please clarify if all your csv files have the same column names and you want to import them all into a single data frame or if you want to import each csv into a different data frame?

Tried this code but for each data frame all column names are taking as single variable and it is accepting all format files like csv, ipynb,xlsx

But my team would like to have it in for loop

All the column names are same for all csv files and I need to import each csv into different data frame
Thank you

Then you can do something like this

for (i in list.files(path = "path/to/your/files", pattern = "\\.csv$")) {
    assign(sub("\\.csv", "", i), read.csv(i))
}
1 Like

:blush: thank you very much

It helped me .

Thank you very much !! It worked

And could I also ask one more doubt in R ggplot

I got the graph perfectly, but u know on the x-axis I was trying to plot values but I am not getting it.

I got a data frame which has 3 columns
I need to plot 2nd column which contains years from 201201 to 201912 I need to plot all the years on x-axis
Could you please help me with that?

This is a very different question, we like to keep things tidy around here so just one reasonably well defined question per topic and closely related follow ups. Can you please ask this on a new topic providing a relevant REPRoducible EXample (reprex) for your new issue?

2 Likes

This topic was automatically closed 42 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.