C paul
C paul

Reputation: 31

Can I use a for loop in R to write in a high number of .csv files in R?

I'm trying to save 50 of .csv files in R. From there, I want to run some code which selects specific words in a column I know I could do this individually, but it would obviously take a very long time. Is there a faster way to do this? This is what I would have to do 50 times

d100 <- read.csv("hello100_mynameis", header = FALSE)
S100 = sum(df100$A5 =='My') + sum(df100$A5 == 'Name') 
S100

df110 <- read.csv("hello110_mynameis", header = FALSE)
S110 = sum(df110$A5 =='My') + sum(df110$A5 == 'Name') 
S110

df120 <- read.csv("hello120_mynameis", header = FALSE)
S120 = sum(df120$A5 =='My') + sum(df120$A5 == 'Name') 
S120

My understanding is that a for loop would be best for this:

number = c(100, 110, 120)

for(i in number){
df[i] <- read.csv("hello[number]_mynameis.csv", header = FALSE)
} 

I didn't really think this code would work and as expected it doesn't. So essentially, I want the 50 csv files to be saved in R under df100, df110, df120 etc...

I get the following error:

In file(file, "rt") :
cannot open file 'hello[number]_mynameis.csv': No such file or directory

which makes sense because I don't have a file called hello[number]_mynameis.csv, but I don't know what else to do. Thank you for any help!

Upvotes: 0

Views: 67

Answers (3)

SymbolixAU
SymbolixAU

Reputation: 26258

You can use assign to create objects in the environment

for(i in number){
    assign(paste0("new_df_",i), read.csv(paste0("hello[",i,"]mynameis.csv"), header = FALSE))
}

Here's a working example

df1 <- data.frame(id = 1:5)
df2 <- data.frame(id = 6:10)

number <- 1:2

for(i in number){
    assign(paste0("new_df_",i), get(paste0("df", i)))
}

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522719

Use a paste function:

number <- c(100, 110, 120)
df <- list()

for (i in number) {
    file <- paste0("hello", i, "_mynameis.csv")
    df[[i]] <- read.csv(file, header=FALSE)
} 

Upvotes: 1

akrun
akrun

Reputation: 887881

It is better to read it in a list rather than creating multiple objects in the global env, i.e.

files <- sprintf("hello%d_mynameis.csv", number)
library(data.table)
lapply(files, function(x) fread(x)[, sum(A5 %chin% c("My", "Name"))]) 

Upvotes: 2

Related Questions