2016-11-02 4 views
1

Ich habe eine Funktion, die eine sehr große Textdatei Zeile für Zeile einliest. Ich erstelle eine Liste mit NAs, bevor ich meine Funktion verwende.So speichern Sie Werte außerhalb der Funktion

Die Funktion fügt +1 zu einer bestimmten Position innerhalb der Liste hinzu, wenn eine bestimmte Bedingung erfüllt ist. Aber das funktioniert nur innerhalb der Funktion. Wenn ich meine Liste drucke, nachdem ich sie angewendet habe, wird wieder die ursprüngliche Liste angezeigt (gefüllt mit NAs).

Wie kann ich die Werte so speichern, dass ich sie außerhalb der Funktion verwenden kann?

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

Konnten Sie die Ausgabe nicht zurückgeben und sie in eine Variable wie return (lion) schreiben? –

Antwort

0

Sie entweder die Liste als der letzte Teil Ihrer Funktion zurückzukehren:

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) 
} 

Auf diese Weise können Sie Ihre Funktion mit lion <- processFile(yourfile)

Alternativ nennen kann, Sie können die Liste beim Ausführen der Funktion dem .GlobalEnv zuweisen:

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) 
} 
Verwandte Themen