I have a folder with 40 files (although I want to write the code so that it works with any number of files as this will come up all the time for me). All I want to do is obtain a new file that compiles all those files together as columns. Each file contains 5 columns, each with 902 rows.
This is what I wrote:
Specs2 <- function()
{
allspecs2 <- NULL
fnames2 <- scan(file.choose(), what = "character", quiet = TRUE)
print(fnames2)
for (i in fnames2)
{
dat2 <- read.table(paste("E:\\Post-doc Data\\Colour- Temperature\\Compiled Sets Rows\\",i, sep=""))
value <- data.frame(dat2)
allspecs2 = cbind(allspecs2, value)
}
allspecs2 <- data.frame(allspecs2)
write.table(allspecs2, "E:\\Post-doc Data\\Colour- Temperature\\Colour-Temperature_Columns.csv", row.names = FALSE, quote = FALSE)
}
Specs2()
When prompted to choose file I choose a file which contains the list of all the files in the folder I want to compile. When I run this code I get the following error code:
"Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 902"
but all the files that I am compiling have the same number of rows and columns. Does anybody know why I'm getting this error or how to fix it? or a different way of coding it to achieve the same thing?
Thank you!
EDIT: So after reading MrFlicks answer, I understand why his code works but I've used the same type of code before with success:
Specs1 <- function()
{
allspecs1 <- NULL
dirnames <- scan(file.choose(), what = "character", quiet = TRUE)
print(dirnames)
for (j in dirnames)
{
fnames1 <- list.files(path = paste("E:\\Post-doc Data\\Colour-Temperature\\Specs\\",j, sep = ""), pattern = NULL, all.files = FALSE,
full.names = FALSE, recursive = FALSE,
ignore.case = TRUE, include.dirs = FALSE, no.. = FALSE)
print(fnames1)
for (i in fnames1)
{
dat1 <- read.table(paste("E:\\Post-doc Data\\Colour-Temperature\\Specs\\",j,"\\",i, sep=""), skip = 17)
smoothed <- ksmooth(dat1[,1], dat1[,2], kernel = "box", bandwidth = 10, x.points = seq(300, 2100, 2))
allspecs1 = cbind(allspecs1, smoothed$y)
}
allspecs1 = cbind(smoothed$x, allspecs1)
allspecs1 <- data.frame(allspecs1)
write.table(allspecs1, paste("E:\\Post-doc Data\\Colour-Temperature\\Compiled Sets Rows\\",j, ".txt"), row.names = FALSE, col.names = FALSE, quote = FALSE)
rm(allspecs1)
allspecs1 = NULL
}
}
Specs1()
I just want to understand why it works some times but not others?
Thank you!