generate for loop for different csv files

Hi,
I have the following code which works successfully



t.test.results<- list()
for (i in 1:6) {
  y=read.csv('Sharpe_window1.csv',header = T)
  y$Data<-NULL
  x1=as.numeric(y[,2])
  y1=as.numeric(y[,i])
  tempdata= augmented_t.test(x1,y1)$diff
  t.test.results[[i]]<- tempdata
}

I want to generate this former code for different csv files and store the results same as what I did before .

I have 4 csv files. I read those files by


for(i in 1:4)
{
  oname = paste("Sharpe_window", i, sep="")
  assign(oname, read.csv(paste(oname, ".csv", sep="")))
}

Now I am trying to generate for loop for each files and store the results for each files as follow:


total.t.test.results<- list()
for (k in 1:4){
 sample.t.test.results<- list()
for (i in 1:6) {
  y=read.csv('Sharpe_window[[k]].csv')
  y$Data<-NULL
  x1=as.numeric(y[,2])
  y1=as.numeric(y[,i])
  tempdata= augmented_t.test(x1,y1)$diff
  sample.t.test.results[[i]]<- tempdata
}
 total.t.test.results[[k]]=sample.t.test.results
}

but I am receiving an error . Can you please help me to solve the problem

This might not be exactly what you are looking for, but based on what you are trying to achieve, it might be a good approach to look into:

# Load Libraries ----------------------------------------------------------
library("tidyverse")
library("broom")


# Create Example Data -----------------------------------------------------
map(1:6, \(i) write_csv(x = tibble(x = rnorm(10), y = rnorm(10)),
                        file = str_c("~/my_csv_file_", i, ".csv")) )


# Load Data ---------------------------------------------------------------
my_csv_files <- list.files(path = "~", full.names = TRUE, pattern = "csv$")
my_data <- my_csv_files %>% 
  map(read_csv)


# Run tests ---------------------------------------------------------------
my_test_results <- my_data %>% 
  bind_rows(.id = "file_number") %>% 
  group_by(file_number) %>% 
  nest %>% 
  ungroup %>% 
  mutate(test = map(data, ~t.test(pluck(.x, "x"),
                                  pluck(.x, "y"), data = .x)),
         tidy_test = map(test, tidy)) %>% 
  unnest(tidy_test) %>% 
  select(-data, -test) %>% 
  mutate(q.value = p.adjust(p.value))

...and hot tip: Want to understand what is going on? Ask chatGPT Please explain the following code in simple terms and then paste the above :+1:

1 Like

Do you mean this to be a literal? Otherwise use

y = read.csv(paste0(“Sharp_window”,k,”.csv”))
1 Like

Thank you very much for your valuable tip !

Thank you very much! it works!!

1 Like

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.