Grouping rows or columns of data in R

I am trying to import some data into R and not delete the grouping of rows of related data.

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

So my input is of 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 a way to keep the structure of this data in R? A similar problem is creating groups of columns (for example, flip the table 90 degrees to the right).

+3
source share
1 answer

: ( ) . , , , {x, y} {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
+4

Source: https://habr.com/ru/post/1727921/


All Articles