file.choose()模拟R中的对象

时间:2016-02-16 12:02:19

标签: r

在R中类似于file.choose()函数,使用R中的对象 (矢量元素,环境中的对象等)? 我需要像file.choose()函数中的对话窗口,我可以在其中选择向量的元素,例如

例如  我有3列数据框架。

length(unique(df$column2))
[1] 3

然后我写

df<- filter(df, column2 %in% MyMagicFunction() )

然后我看到窗口,我选择正确的元素=)

1 个答案:

答案 0 :(得分:0)

我猜你正在使用纯R控制台(即不是RStudio) 在填充了一些假文件后,您可以使用file.choose来查看:

myfunction <- function(df){
  split_path <- function(path) {
    rev(setdiff(strsplit(path,"/|\\\\")[[1]], ""))
  } 


  tmpdir <- file.path("c:/temp",substitute(df))
  dir.create(tmpdir,showWarnings =FALSE)
  for (ivar in names(df)){
    cat("", file=file.path(tmpdir,ivar))
  }
  selvar <- choose.files(default = paste(tmpdir,"*",sep="/"), caption = "Variable",
                         multi = FALSE)
  varname <- split_path(selvar)[1]
  unlink(file.path(tmpdir,"*"))

  print(varname) # to be replaced by your function exploiting df and varname such as mean(df[,varname])

}

然后:

>     doit <- myfunction(iris)
[1] "Sepal.Length"

如评论中所述,您必须在myfunction中定义自己的函数调用。

相关问题