R中的TclTk对象

时间:2014-10-18 03:06:20

标签: r

我是R的新手(以及一般的编程),如果在其他地方已经回答了这个问题,那么道歉。我无法通过搜索找到答案,但任何帮助或方向都会很棒!

我正在尝试在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

再一次,非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分: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退出。

相关问题