0

Within R for Mac I'm trying to create a bash file that, by double clicking outside of R, creates folders in a specific path directory set within R. The number of folders should be equal to a vector (set within R). This following code works within R for windows, but just replacing the extension ".bat" to ".sh" doesn't seem to work.

vec <- c(1,1,1)
bat<-matrix(nrow=length(vec),ncol=2,0)
        for (i in 1:length(vec)){
            bat[i,1]<-"md"
            bat[i,2]<-gsub("/","/",paste(saveloc,"/",vec[i],sep=""),fixed=T)
        }
        write.table(bat,paste(saveloc,"/","individual names.bat",sep=""),sep=" ",dec=dec,row.names=F,col.names=F,quote=2)

"Saveloc" is the path directory. Any ideas how I can make this happen on a mac?

Any help is greatly appreciated.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
FlyingDutch
  • 1,100
  • 2
  • 14
  • 24
  • Is it absolutely necessary to create a shell script? Because you can use R to create directories, see `dir.create()` – kgolyaev Feb 11 '18 at 17:26
  • Not necessary at all, it's just what I know works (at least for windows). I'll have a look at your suggestion. – FlyingDutch Feb 11 '18 at 17:29
  • I'm not sure how to finish your process which seems a bit vague at the moment, but I'm pretty sure you will eventually need to mark a bash script as executable. You should be able to search for "HowTo" do that in Unix commands. – IRTFM Feb 11 '18 at 17:42
  • "How do I run a shell script without using “sh” or “bash” commands? " https://stackoverflow.com/questions/8779951/how-do-i-run-a-shell-script-without-using-sh-or-bash-commands – IRTFM Feb 11 '18 at 17:48
  • @kgolyaev Your solution seems to work with just a simple "for" loop, iterating through the vector and creating subfolders within a designated folder. Could you write an official answer so i can mark this question as answered? – FlyingDutch Feb 11 '18 at 17:51
  • Instead of `md` for making directories, try `mkdir`. – Neal Fultz Feb 11 '18 at 17:57

1 Answers1

1

Here is how you can do this in R without the shell scripts:

# make up a small nested folder structure
dirsToCreate <- cbind(
  rep("top", 6), 
  rep(c("middle1", "middle2"), each=3), 
  rep(c("bottom1", "bottom2", "bottom3"), 2)
)
dirsToCreate <- apply(
  dirsToCreate, 1, function(x) paste(x, collapse="/"))
# here are the folders we will create
dirsToCreate
[1] "top/middle1/bottom1" "top/middle1/bottom2"
[3] "top/middle1/bottom3" "top/middle2/bottom1"
[5] "top/middle2/bottom2" "top/middle2/bottom3"
# now actual creation, in a loop
for (d in dirsToCreate) {
  dir.create(d, recursive = TRUE)
}
kgolyaev
  • 565
  • 2
  • 10