[R] How to import variable length lists of lists into R from text file?
jim holtman
jholtman at gmail.com
Tue Mar 29 00:38:23 CEST 2011
Try this -- I added commas in the first line (header) so it looks like
a CSV file:
> x <- textConnection('V1, V2 , V3 , V4 , V5
+ 1, 2.3, "Bob", {1.7,2.3,3.4}, 4.5
+ 2, 3.4, "Carol", {}, 3.4
+ 3, 2.2, "Ted", {1.0,2.5}, 3.5')
> # read in the lines and then replace {} with quotes
> x.line <- readLines(x)
> close(x)
> x.line.q <- chartr("{}", '""', x.line)
> # now re-read the data
> input <- read.csv(textConnection(x.line.q), as.is = TRUE)
> closeAllConnections()
> input
V1 V2 V3 V4 V5
1 1 2.3 Bob 1.7,2.3,3.4 4.5
2 2 3.4 Carol 3.4
3 3 2.2 Ted 1.0,2.5 3.5
>
On Mon, Mar 28, 2011 at 6:03 PM, Britt Anderson
<britt.uwaterloo at gmail.com> wrote:
> I will be collecting data where one of the fields may be of length
> zero to some variable number of elements, along with other items of
> fixed size.
>
> As an illustration if mydata.dat is:
>
> V1 V2 V3 V4 V5
> 1, 2.3, "Bob", {1.7,2.3,3.4}, 4.5
> 2, 3.4, "Carol", {}, 3.4
> 3, 2.2, "Ted", {1.0,2.5}, 3.5 ...
> ...
>
> I want to be able to do something like mydata <-
> read.csv("./mydata.dat") and have the field with curly braces live in
> a single cell of the data frame as a potentially empty list of
> floating point numbers. Is this possible? I am creating the text file
> so I can put in whatever characters would be useful to facilitate this
> operation. The curly braces are just for example purposes.
>
> Thank you,
> Britt Anderson
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list