чтение текстового файла в строке R
Я хотел бы прочитать текстовый файл в R, строка за строкой, используя цикл for и длину файла. Проблема в том, что он печатает только символ (0). Это код:
fileName="up_down.txt" con=file(fileName,open="r") line=readLines(con) long=length(line) for (i in 1:long){ linn=readLines(con,1) print(linn) } close(con)
- Чтение всего текстового файла в массив символов в C
- Водяной знак / текст подсказки / заполнитель TextBox
- ReadAllLines для объекта Stream?
- PrintWriter vs FileWriter в Java
- Как нажимать или нажимать текст TextView на разные слова?
- Лучший способ конвертировать текстовые файлы между наборами символов?
- Необязательно вводить сценарий контента
- Определение типа двоичного / текстового файла в Java?
- Использование BufferedReader для чтения текстового файла
- Автомасштабирование текста TextView для вставки в пределах границ
- Запись в начале текстового файла Java
- Обновление Android TextView в streamе и Runnable
- Android TextView Обоснование текста
Вы должны заботиться о readLines(...)
и больших файлах. Чтение всех строк в памяти может быть рискованным. Ниже приведен пример того, как читать файл и обрабатывать только одну строку:
processFile = function(filepath) { con = file(filepath, "r") while ( TRUE ) { line = readLines(con, n = 1) if ( length(line) == 0 ) { break } print(line) } close(con) }
Понять риск чтения строки в памяти тоже. Большие файлы без разрывов строк также могут заполнить вашу память.
Просто используйте readLines
в своем файле:
R> res <- readLines(system.file("DESCRIPTION", package="MASS")) R> length(res) [1] 27 R> res [1] "Package: MASS" [2] "Priority: recommended" [3] "Version: 7.3-18" [4] "Date: 2012-05-28" [5] "Revision: $Rev: 3167 $" [6] "Depends: R (>= 2.14.0), grDevices, graphics, stats, utils" [7] "Suggests: lattice, nlme, nnet, survival" [8] "[email protected]: c(person(\"Brian\", \"Ripley\", role = c(\"aut\", \"cre\", \"cph\")," [9] " email = \"[email protected]\"), person(\"Kurt\", \"Hornik\", role" [10] " = \"trl\", comment = \"partial port ca 1998\"), person(\"Albrecht\"," [11] " \"Gebhardt\", role = \"trl\", comment = \"partial port ca 1998\")," [12] " person(\"David\", \"Firth\", role = \"ctb\"))" [13] "Description: Functions and datasets to support Venables and Ripley," [14] " 'Modern Applied Statistics with S' (4th edition, 2002)." [15] "Title: Support Functions and Datasets for Venables and Ripley's MASS" [16] "License: GPL-2 | GPL-3" [17] "URL: http://www.stats.ox.ac.uk/pub/MASS4/" [18] "LazyData: yes" [19] "Packaged: 2012-05-28 08:47:38 UTC; ripley" [20] "Author: Brian Ripley [aut, cre, cph], Kurt Hornik [trl] (partial port" [21] " ca 1998), Albrecht Gebhardt [trl] (partial port ca 1998), David" [22] " Firth [ctb]" [23] "Maintainer: Brian Ripley " [24] "Repository: CRAN" [25] "Date/Publication: 2012-05-28 08:53:03" [26] "Built: R 2.15.1; x86_64-pc-mingw32; 2012-06-22 14:16:09 UTC; windows" [27] "Archs: i386, x64" R>
Существует полное руководство, посвященное этому …
Вот решение с циклом for
. Важно отметить, что один вызов readLines
выходит из цикла for, чтобы он не вызывался неправильно и снова. Вот:
fileName <- "up_down.txt" conn <- file(fileName,open="r") linn <-readLines(conn) for (i in 1:length(linn)){ print(linn[i]) } close(conn)
Я пишу код для чтения файла по строкам, чтобы удовлетворить мое требование, в котором разные строки имеют разные типы данных, следуя статьям: read-line-by-of-a-file-in-r и define-number-of-linesrecords . Думаю, это должно быть лучшим решением для большого файла. Моя версия R (3.3.2).
con = file("pathtotargetfile", "r") readsizeof<-2 # read size for one step to caculate number of lines in file nooflines<-0 # number of lines while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file nooflines<-nooflines+linesread con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (eg numeric)and second line has same type with 'c' (eg character). This meet my demand. for(i in 1:nooflines) { tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE) print(is.vector(tmp)) print(tmp) } close(con)