2016-11-02 13 views
1

非常に大きなテキストファイルを1行ずつ読み込む関数があります。 私は自分の機能を使う前にNAで満たされたリストを作成します。関数外で使用する値を格納する方法

この機能は、特定の条件が満たされたときにリスト内の特定の位置に+1を追加します。しかし、これは何らかの形で機能の内部でしか機能しません。私がそれを適用した後に私のリストを印刷すると、やはり最初のリストが表示されます(NAで埋められます)。

どのように私は関数の外で使用できるように値を格納できますか?

lion<-lapply(1, function(x) matrix(NA, nrow=2500, ncol=5000))

processFile = function(filepath) { 
    con = file(filepath, "rb") 

    while (TRUE) { 
    line = readLines(con, n = 1) 
    if (length(line) == 0) { 
     break 
    } 
    y <- line 
    y2 <- strsplit(y, "\t") 
    x <- as.numeric(unlist(y2)) 
    if(x[2] <= 5000 & x[3] <= 2500) { 

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])] 
    } 
    } 

    close(con) 

} 
+3

出力を返してreturn(lion)のような変数に書き込むことはできませんか? –

答えて

0

あなたのいずれかが、あなたの関数の最後の部分としてリストを返すことがあります。

processFile = function(filepath) { 
    con = file(filepath, "rb") 

    while (TRUE) { 
    line = readLines(con, n = 1) 
    if (length(line) == 0) { 
     break 
    } 
    y <- line 
    y2 <- strsplit(y, "\t") 
    x <- as.numeric(unlist(y2)) 
    if(x[2] <= 5000 & x[3] <= 2500) { 

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])] 
    } 
    } 

    close(con) 
    return(lion) 
} 

この道を、あなたはまたlion <- processFile(yourfile)

であなたの関数を呼び出すことができ、関数を実行しているときに.GlobalEnvにリストを割り当てることができます。

processFile = function(filepath) { 
    con = file(filepath, "rb") 

    while (TRUE) { 
    line = readLines(con, n = 1) 
    if (length(line) == 0) { 
     break 
    } 
    y <- line 
    y2 <- strsplit(y, "\t") 
    x <- as.numeric(unlist(y2)) 
    if(x[2] <= 5000 & x[3] <= 2500) { 

    lion[[1]][trunc(x[3] + 1), trunc(x[2])] <- lion[[1]][trunc(x[3] + 1), trunc(x[2])] 
    } 
    } 

    close(con) 
    assign("lion", lion, envir = .GlobalEnv) 
} 
関連する問題