0

I want to check all CSV files in a folder and count its number of columns, and for whichever file has 12 columns I want to save it in another folder

I tried the following code but it doesn't work for me.

Folder <- "E:/Extracted Tables/"
files <- list.files(path = Folder, pattern = "*.csv", full.names = TRUE )
Sheet= NULL

for (i in seq_along(files)){
  Sheet[i]= as.data.frame(read.csv(files[i], header = FALSE, sep =",")%>%mutate_all(as.character))
  if(ncol(Sheet[i])==12){
      write.csv(Sheet[i],paste("E:/Extracted Tables/SortedFiles/",Sheet[i],".csv"))
  }
 }

I am getting the following error:

Error in if (ncol(Sheet[i]) == 12) { : argument is of length zero
In addition: Warning message:
In Sheet[i] <- as.data.frame(read.csv(files[i], header = FALSE,  :
  number of items to replace is not a multiple of replacement length
zx8754
  • 52,746
  • 12
  • 114
  • 209
  • Possible duplicate of these 2 posts: you need to address the errors and warning, see https://stackoverflow.com/questions/27350636/r-argument-is-of-length-zero-in-if-statement and https://stackoverflow.com/questions/38738347/why-do-i-get-number-of-items-to-replace-is-not-a-multiple-of-replacement-length – zx8754 Oct 02 '20 at 05:53
  • There is not need for as.data.frame, read.csv returns a dataframe. There is no need for mutate_all, you can set colClasseses within read.csv. – zx8754 Oct 02 '20 at 05:55
  • Hi, i guess that post is not what i was looking for, my question was rather different... anyways i had found a workaround. WIll post that solution here soon – Aftab Udaipurwala Oct 06 '20 at 10:42

0 Answers0