2017-09-13 178 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))