Using purrr::walk to save the files - invalid 'description' argument
I have problems with saving files using looping. I first wrote a function which works well without loop. However, it always fail with loop. Can anybody tell me the reason?
a<-c(1,2,3)
b<-c(4,5,6)
c<-c(7,8,9)
data<-data.frame(a,b,c)
path<-list('path1/', 'path2/')
test<-function(data,path){
write.csv(data,file = paste0(path,'result.csv'))
}
purrr::walk(path, test(data=data, path=path))
# Warning in if (file == "") file <- stdout() else if (is.character(file)) { :
# the condition has length > 1 and only the first element will be used
# Error in file(file, ifelse(append, "a", "w")) :
# invalid 'description' argument
The warning about condition has length
is because you are passing path=path
which is length 2, and the file=
argument of write.csv
expects length 1.
You think that you're using walk
to iterate over values, but you need to use a function or ~
quasi-function.
This works:
purrr::walk(path, ~ test(data=data, path=.))
The .
can also be .x
and is a placeholder for each of the values within the first argument to walk: path
. A "standard" function use would be
purrr::walk(path, function(P) test(data=data, path=P))
(which also works).