[R] scan - open text file as list

Hermann Norpois hnorpois at gmail.com
Wed Apr 15 21:47:11 CEST 2015


Thanks.
Actually, I thought there was a way to do it with scan only ...


2015-04-15 16:40 GMT+02:00 William Dunlap <wdunlap at tibco.com>:

> > strsplit(x=sub(pattern="^\\* ", replacement="", x=test), split=" ")
> [[1]]
> [1] "a" "b" "d"
>
> [[2]]
> [1] "z"  "u"  "i"  "h"  "hh"
>
> [[3]]
> [1] "h"  "bh" "kk"
>
>
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
>
> On Tue, Apr 14, 2015 at 2:34 PM, Hermann Norpois <hnorpois at gmail.com>
> wrote:
>
>> Hello,
>>
>> I try to open a text file test.txt with the content
>>
>> * a b d
>> * z u i h hh
>> * h bh kk
>>
>> so that I get a list with each line as a vector with the letters as
>> elements of the the vector.
>>
>> My approach ...
>> test <- scan ("test.txt", what="character", sep="\n")
>> Read 3 items
>> > test.list <- lapply (test, function (x) {a <- unlist (strsplit(x," "));
>> a
>> <- a[-1]})
>> > test.list
>> [[1]]
>> [1] "a" "b" "d"
>>
>> [[2]]
>> [1] "z"  "u"  "i"  "h"  "hh"
>>
>> [[3]]
>> [1] "h"  "bh" "kk"
>>
>> ... the result is okay but I dont think it is an elegant solution. One
>> comment: I dont know how many lines my "real" test.txt will have.
>> Thanks Hermann
>>
>>         [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list