overdisperse
overdisperse

Reputation: 426

Get values of variables during warning inside for-loop (R)

I'm trying to batch convert a bunch of files as follows:

library(foreign)

for(dtaf in dir(recursive=TRUE,pattern="\\.dta$")){
  write.csv(read.dta(dtaf),paste0(substr(dtaf,1,nchar(dtaf)-3),"csv"))
  gc()
}

However, once the loop is done, I get the following warnings:

Warning messages:
1: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated
2: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated
3: In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
  duplicated levels in factors are deprecated

I'd like to know if there's a way to retrieve the value of dtaf (the file being currently written) so I can manually examine it and see if there's any actual issue with the data.

Upvotes: 1

Views: 249

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145975

tryCatch is most commonly used for catching errors, but it can also be used for warnings.

Something like

 tryCatch(write.csv(<your code>), warning = function(w) print(dtaf))

will print(dtaf) whenever there is a warning. You could make the warning function as elaborate as you would like, maybe printing out the warning too, adding the warning and the dtaf value to a list for later review, etc.

Upvotes: 1

Related Questions