tags:

views:

266

answers:

1

I'm trying to import some data into R and not having much luck grouping together rows of related data.

Example: There a set of problems such as {A, B, C, D}. Each problem has two variables of interest which are being measured: "x" and "y". Each variable is analysed in terms of some simple statistics: min, max, mean, stddev.

So, my input data has the form:

      Min  Max  Mean  StdDev
A
  x   3    10   6.6   2.1 
  y   2    5    3.2   1.7
B
  x   3    10   6.6   2.1 
  y   2    5    3.2   1.7
C
  x   3    10   6.6   2.1 
  y   2    5    3.2   1.7
D
  x   3    10   6.6   2.1 
  y   2    5    3.2   1.7

Is there any way to preserve the structure of this data in R? A similar problem is creating groups of columns (flip the table by 90 degrees to the right for example).

+4  A: 

You actually have many options: a data frame (relational table), or list. The following code will show how to create a data frame, and then to split it into a list containing the elements {x,y} or {A,B,C,D}:

> txt <- "      Min  Max  Mean  StdDev
+ A
+   x   3    10   6.6   2.1 
+   y   2    5    3.2   1.7
+ B
+   x   3    10   6.6   2.1 
+   y   2    5    3.2   1.7
+ C
+   x   3    10   6.6   2.1 
+   y   2    5    3.2   1.7
+ D
+   x   3    10   6.6   2.1 
+   y   2    5    3.2   1.7
+ "
> 
> data <- head(readLines(textConnection(txt)),-1)
> fields <- strsplit(sub("^[ ]+","",data[!nchar(data)==1]),"[ ]+")
> DF <- `names<-`(data.frame(rep(data[nchar(data)==1],each=2), ## letters
+                            do.call(rbind,fields[-1])),       ## data
+                 c("Letter","xy",fields[[1]]))                ## colnames
> split(DF,DF$xy)
$x
  Letter xy Min Max Mean StdDev
1      A  x   3  10  6.6    2.1
3      B  x   3  10  6.6    2.1
5      C  x   3  10  6.6    2.1
7      D  x   3  10  6.6    2.1

$y
  Letter xy Min Max Mean StdDev
2      A  y   2   5  3.2    1.7
4      B  y   2   5  3.2    1.7
6      C  y   2   5  3.2    1.7
8      D  y   2   5  3.2    1.7

> split(DF,DF$Letter)
$A
  Letter xy Min Max Mean StdDev
1      A  x   3  10  6.6    2.1
2      A  y   2   5  3.2    1.7

$B
  Letter xy Min Max Mean StdDev
3      B  x   3  10  6.6    2.1
4      B  y   2   5  3.2    1.7

$C
  Letter xy Min Max Mean StdDev
5      C  x   3  10  6.6    2.1
6      C  y   2   5  3.2    1.7

$D
  Letter xy Min Max Mean StdDev
7      D  x   3  10  6.6    2.1
8      D  y   2   5  3.2    1.7
Stephen
Thanks Stephen. That was very helpful.
Daniel