R:列和/或行上的多索引 [英] R: multi-index on columns and/or rows
问题描述
在 python
中,更具体地说,在 pandas
中,我可以使用 MultIndex
在行或列上。 R
是否有等效项?我正在检查几个教程,例如 https://en.wikibooks.org/wiki/ R_Programming / Working_with_data_frames ,但我找不到合适的 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.
我有以下数据框:
A-1 A-2 B-1 B-2
0 1 2 0 1
1 2 0 1 3
2 4 1 3 2
I希望它看起来像这样:
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
我有其他相关答案从stackoverflow中找到
Other relevant answers I have found from stackoverflow
- Set columns as index
- Paste multiple columns to an index
推荐答案
鉴于您正在寻找一种解决方法,我会给您一个有限的答案。 R中的数组只能保留一种模式(这与大多数人的理解相反,可以包括列表)
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
这篇关于R:列和/或行上的多索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!