[R] Read data in sequences
Phil Spector
spector at stat.berkeley.edu
Fri Apr 9 19:16:52 CEST 2010
Rock -
Here's one way:
> x = textConnection('A 2.5 3.4 2.7 5.6 5.7 5.4 10.1 9.4
+ B 5.3 5.4 6.5 7.5 1.3 4.5 10.5 4.1')
> dat = read.table(x)
> names(dat) = c('grp','x1','x2','x3','x4','x5','x6','x7','x8')
> reshape(dat,idvar='grp',varying=list(c('x1','x3','x5','x7'),
+ c('x2','x4','x6','x8')),
+ direction='long',timevar=NULL)
grp x1 x2
A.1 A 2.5 3.4
B.1 B 5.3 5.4
A.2 A 2.7 5.6
B.2 B 6.5 7.5
A.3 A 5.7 5.4
B.3 B 1.3 4.5
A.4 A 10.1 9.4
B.4 B 10.5 4.1
You could generalize the varying argument like this:
mkvarying = function(n)list(paste('x',seq(1,n,by=2),sep=''),
paste('x',seq(2,n,by=2),sep=''))
and use
reshape(dat,idvar='grp',varying=mkvarying(8),direction='long',timevar=NULL)
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Fri, 9 Apr 2010, RockO wrote:
>
> Dear R users,
>
> I tried to find a solution in the search list, but I cannot find it. I would
> like to read a .txt file with, let say, three variables, with two of which
> have repeated values in a number a columns.
>
> An example:
>
> The variables: Treat, x1, x2.
> The values:
> A 2.5 3.4 2.7 5.6 5.7 5.4 10.1 9.4 ...
> B 5.3 5.4 6.5 7.5 1.3 4.5 10.5 4.1 ...
> ...
>
> In the first column, the letters represent the variable "Treat", and the
> sequence of numbers on a same line represent pairs of values for "x1" and
> "x2".
>
> In SAS, this type of dataset is easy to read using "@@" as in:
> data a;
> input Treat @ x1 x2 @@;
>
> But I would like to know how to read it with R, to get rid of my addiction
> to SAS.
>
> Thank You,
>
> Rock Ouimet
> DRF-MRNF, Quebec
> --
> View this message in context: http://n4.nabble.com/Read-data-in-sequences-tp1819487p1819487.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list