Creating separate variables from different files in R

Hi there,
I'm trying to perform a fourier transformation on several different files at once, and I'd like to save the resulting vectors of each file as variables with different names so that I can later compile them into 1 dataset. At the moment when I try to print the results I can only obtain results for the 1st file in the list of files. I'd really appreciate a suggestion as to how to give each output a different name so I can access all of them.

rm(list=ls(all.names=TRUE))
dataset <- data.frame()
file.list <- list.files(path="", setnames=TRUE)
> 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))
+ 
+ fourierd <- apply(my_data,2,function(x) fft(as.numeric(x))) #it's now a matrix
+ 
+ fourierdat <- as.data.frame(fourierd)
+ 
+ 
+ absTestAll <- abs(fourierdat) 
+ 
+ 
+ histData <- sapply(absTestAll[2:nrow(absTestAll),], which.max) * 0.977 + 0.977
+ histData.df <- as.data.frame(histData)
+ }

Hello.
The main assistance I can give you is how to save the outputs to their own names rather than the common histData.df name that your code funnels them all into. the assign(x,value) is useful for this.
Since you capture the base of the name into your title1 variable that would be a good place to start.
if title1 has arbitrary content like 'example1' you could then have your code at the the end do something like :

h̶i̶s̶t̶D̶a̶t̶a̶.̶d̶f̶ ̶<̶-̶ ̶a̶s̶.̶d̶a̶t̶a̶.̶f̶r̶a̶m̶e̶(̶h̶i̶s̶t̶D̶a̶t̶a̶)̶
 assign(title1, histData)

and at that point in the loop a variable called example1 would be assigned the histData contents.

There are other minor issues to contend with in your code as posted here...
I suspect that rather only being able to access the first file, you are able to access the last, if first is defined by corresponding to i==1 and last i==length(file_list).

There's also an inconsistency in your code about the file.list which is then referred to as file_list so your code wont actually execute as written. I noticed also an error on the list.files() function as this has no setname param. I had to remove it to prove to myself it worked right.

When you tidy these issues up, you'll be good to go :slight_smile:

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