2017-09-13 195 views
0

我有我的代码的问题,其中函数不会返回任何东西。这是有问题的代码:函数不返回结果

#Required libraries: rJava, rChoiceDialogs, tcltk 


#Set the working directory 
set_library = function(){ 
    library(rJava) 
    library(rChoiceDialogs) 
    wd = jchoose.dir() 
    setwd(wd) 
    return(wd) 
} 

#Load the csv files 
load_files = function(){ 
    library(tcltk) 
    stocks = tk_choose.files() 
    print(length(stocks)) 
    return(stocks) 
} 

set_library() 
load_files() 
print(length(stocks)) 

功能将打印在load_files功能,但不是在最后的长度。

+2

问题在于变量的范围,以解决它,你可以:_1:_店的变量函数,比如'库存量<结果 - load_files( )'然后尝试'print(length(stocks1))'或_2:_使用'<< - '作为全局环境赋值为'stocks << - tk _.......' – parth

+0

'stocks'是定义在'load_files'函数中,这是一个本地对象。因此它不能在函数之外访问。 – TUSHAr

回答

0

您需要保存stocks父范围:

# Required libraries: rJava, rChoiceDialogs, tcltk 

# Set the working directory 
set_library = function() { 
    library(rJava) 
    library(rChoiceDialogs) 
    wd = jchoose.dir() 
    setwd(wd) 
    return(wd) 
} 

# Load the csv files 
load_files = function() { 
    library(tcltk) 
    stocks = tk_choose.files() 
    # print(length(stocks)) 
    return(stocks) 
} 

set_library() 
stocks <- load_files() 
print(length(stocks))