Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: multi-index on columns and/or rows

Tags:

dataframe

r

In python, and more specifically in pandas, I can work with MultIndex on rows or columns. Is there an equivalent in R? I was checking several tutorials, such as the one in https://en.wikibooks.org/wiki/R_Programming/Working_with_data_frames, but I couldn't find a proper R equivalent.

As an example I have the following data frame:

   A-1  A-2 B-1 B-2
0  1    2    0   1
1  2    0    1   3
2  4    1    3   2

I want it to look like:

   A         B
   1    2    1   2
0  1    2    0   1
1  2    0    1   3
2  4    1    3   2

Other relevant answers I have found from stackoverflow

  1. Set columns as index
  2. Paste multiple columns to an index
like image 828
goofd Avatar asked Jun 19 '15 17:06

goofd


People also ask

How do I address multiple columns in R?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.

Do columns or rows come first in R?

As others have said, the structure within brackets is row , then column . [dframe$Name=="AADAM",] is the verb. It is the action you want to perform.


1 Answers

Given that you were looking for a "work around" I will give you an admittedly limited one. Arrays in R can only hold one mode (which contrary to most people's understanding can include lists)

>   arr1 <- matrix(scan(), 3,byrow=TRUE) 
1:   1    2    0   1
5:   2    0    1   3
9:   4    1    3   2
13: 
Read 12 items
> arr2 <- array(arr1, c(3,2,2))  # Re-dimensioning can also be done with `dim<-`
> arr2
, , 1

     [,1] [,2]
[1,]    1    2
[2,]    2    0
[3,]    4    1

, , 2

     [,1] [,2]
[1,]    0    1
[2,]    1    3
[3,]    3    2

> dimnames(arr2) <- list( rows=0:2, subcat=1:2, majorcat=c("A","B") )
> arr2
, , majorcat = A

    subcat
rows 1 2
   0 1 2
   1 2 0
   2 4 1

, , majorcat = B

    subcat
rows 1 2
   0 0 1
   1 1 3
   2 3 2

After setting this up, there is a display method that delivers something like what you requested:

> ftable(arr2, row.vars=1)
     subcat   1   2  
     majorcat A B A B
rows                 
0             1 0 2 1
1             2 1 0 3
2             4 3 1 2

Looks like I needed to specify it differently :

> ftable(arr2, row.vars=1, col.vars=3:2)
     majorcat A   B  
     subcat   1 2 1 2
rows                 
0             1 2 0 1
1             2 0 1 3
2             4 1 3 2
like image 88
IRTFM Avatar answered Oct 05 '22 11:10

IRTFM