2014-01-07 40 views
6

我試圖在R中複製shell命令,但無法弄清楚如何將命令串在一起。這只是返回的工作文件夾中的內容(system()由於某種原因失敗):Windows中的多個shell命令

> shell("dir") 
Volume info .. 
Directory of E:\Documents\R 
contents are listed.. 

現在讓我們嘗試並導航到C盤並運行dir(不使用明顯dir C:)..

> shell("cd C:") 
C:\ 
> shell("dir") 
Volume in drive E is GT 
etc.. 

所以看起來命令不能單獨輸入,因爲shell不記得工作目錄。所以..

> (cmd = "cd C: 
+ dir") 
[1] "cd C:\ndir" 
> shell(cmd) 
C:\ 

沒有運氣,因爲C:文件夾沒有報告。我試過的其他方法也失敗了。感謝任何想法。

+0

作爲康拉德指出,有更好的方法來獲得'R'完成任務。例如,使用具有指定路徑名的'R'的'dir'函數。 'dir(path ='E:/ documents/r',pattern ='whatever ...')' –

回答

2

我在Linux上,這對我的作品:

system("cd ..;ls") 

導航到以前的目錄並運行LS/DIR那裏。在你的情況下,在Windows上,這顯然作品:

shell("cd C: & dir") 

或得到輸出字符向量:

shell("cd C: & dir", intern=T)和Linux上:system("cd ..; ls", intern=T)

+1

Works works thanks! shell(「cd C:&dir」,intern = T)'返回字符向量 – geotheory

+1

該文檔特別指出,這在Windows上不起作用。 –

+1

是使用shell而不是系統 – geotheory

1

不知道這是否會有所幫助,但在Mac OS使用system作品時崩潰的命令,將一個字符串

cmds <- c("ls", "cd ..", "ls"); 
system(paste(cmds, collapse=";")) 
+0

該文檔特別指出,這在Windows上不起作用。 –

+0

@Konrad Rudolph:Uups,抱歉,錯過了... –

4

The documentation解釋了爲什麼system不起作用:它直接在Windows上執行命令,而不首先產生shell。

shell(或更好,system2)是要走的路,但因爲你已經注意到,shell總是會催生一個新外殼使對環境的更改不會轉移。 system2不會直接工作,因爲它引用了它的命令(因此不允許鏈接命令)。

正確在這種情況下的解決方案是不使用shell命令來更改目錄。使用setwd代替:

setwd('C:') 
system2('dir') 

如果您希望在執行命令後重置工作目錄,使用以下命令:

local({ 
    oldwd = getwd() 
    on.exit(setwd(oldwd)) 
    setwd('C:') 
    system2('dir') 
}) 
+0

注意到,setwd更好。 – geotheory

0

這是here的解決方案。這解決了我的問題,調用Windows dir命令:

system("cmd.exe /c dir", intern=TRUE)