Create variable for each iteration in a loop

Hi there,
I've set up a loop that goes through a list of files in a folder, performs a transformation on them and then compiles them into a single long list of values in a new dataset. it looks something like this:

file_list <- list.files(path="")
dataset <- data.frame()
for (i in 1:length(file_list)){
my_data <- read.table(file_list[i], header = TRUE,  sep='\t') 
filepath <- file_list[i]
title1<-sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(filepath))
transform <- apply(my_data,2,function(x) fft(as.numeric(x)))
dataset <- rbind(dataset, transform)
}

I'd really like to set up a new function in the loop whereby I can create an extra column in my new dataset which tells me which original file each value is derived from. I've tried adding
cbind(x, title1)
to the function but this causes the loop to only save data from the final iteration to my dataset. Could anyone offer some assistance? Thanks!

I can't test this code since you are not providing a reproducible example but you can do something like this instead of using a loop

library(tidyverse)

file_list <- list.files(path = "",
                        full.names = TRUE)

dataset <- file_list %>% 
    set_names() %>% 
    map_dfr(~{
        read.table(.x, header = TRUE, sep='\t') %>% 
            mutate_all(~fft(as.numeric(.)))
    },
    .id = "title1") %>% 
    mutate(title1 = sub(pattern = "(.*)\\..*$", replacement = "\\1", basename(title1)))

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