2014-10-18 111 views
0

我是R(和一般編程)的新手,很抱歉,如果這已在其他地方得到解答。我無法通過搜索找到答案,但任何幫助或方向都會很棒!R中的TclTk對象

我試圖使R,在那裏我可以讓用戶單擊找到的選擇是繼續在R.

在這裏得到自動分析的文件點擊界面就是我遇到的麻煩是什麼:

require(tcltk) 

getfile <- function() {name <- tclvalue(tkgetOpenFile(
    filetypes = "{{CSV Files} {.csv}}")) 
if (name == "") return; 

datafile <- read.csv(name,header=T) 

} 


tt <- tktoplevel() 
button.widget <- tkbutton(tt, text = "Select CSV File to be analyzed", command = getfile) 
tkpack(button.widget) 
# The content of the CSV file is placed in the variable 'datafile' 

然而,當我嘗試執行它,並在按鈕彈出後單擊感興趣的CSV文件時,什麼也沒有發生。我的意思是當我輸入數據文件時,R給了我下面的錯誤。

Error: object 'datafile' not found 

再次,任何幫助,非常感謝。謝謝!

+0

您只在'getfile()'函數內分配變量'datafile'。該函數存在後,該變量將不復存在。如果你做'datafile << - read.csv(name,header = T)'應該分配給全局環境(假設沒有中間環境有一個名爲'datafile'的變量)。 – MrFlick 2014-10-18 04:29:05

回答

0

頂級對象有一個環境,您可以在其中存儲事物,使它們保持GUI的本地狀態。給你的回調對象作爲參數:

# callback that reads a file and stores the DF in the env of the toplevel: 
getfile <- function(tt) {name <- tclvalue(tkgetOpenFile(
    filetypes = "{{CSV Files} {.csv}}")) 
if (name == "") return; 

tt$env$datafile <- read.csv(name,header=T) 

} 

# callback that does something to the data frame (should check for existence first!)  
dosomething <- function(tt){ 
    print(summary(tt$env$datafile)) 
} 


# make a dialog with a load button and a do something button: 
tt <- tktoplevel() 
button.choose <- tkbutton(tt, text = "Select CSV File to be analyzed", command = function(){getfile(tt)}) 
tkpack(button.choose) 

button.dosomething <- tkbutton(tt, text = "Do something", command = function(){dosomething(tt)}) 
tkpack(button.dosomething) 

這應該是相當強勁的,雖然我不知道是否有任何已有的環境中,你應該小心踩,在這種情況下,創造一個環境環境並將其用於本地存儲。

如果要退出對話框併爲用戶保存內容,請提示輸入名稱,並使用assign在退出時將其存儲在.GlobalEnv中。