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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With