简体   繁体   中英

Hierarchical indexing in R dataframe

I have a CSV file that I'm trying to read into a dataframe in R, and I was wondering how I might go about storing it with hierarchical indexing. In other words, I want to make something with column names like this:

('a1', 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b1', 'c3'), ('a1', 'b1', 'c4'),
('a1', 'b2', 'c1'), ('a1', 'b2', 'c2'), ('a1', 'b2', 'c3'), ('a1', 'b2', 'c4'),
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24

Turn out like this:

_________________________________________________
||                      a1                     ||
_________________________________________________
||          b1          ||          b2         ||
_________________________________________________
||  c1 | c2 | c3 | c4   ||   c1 | c2 | c3 | c4 ||
_________________________________________________
||  1  |  2 |  3 |  4   ||    5 |  6 |  7 |  8 ||
||  9  | 10 | 11 | 12   ||   13 | 14 | 15 | 16 ||
||  17 | 18 | 19 | 20   ||   21 | 22 | 23 | 24 ||
_________________________________________________

When converted into an R dataframe. How exactly would I go about doing that? I am new to R although I'm pretty familiar with Pandas dataframes in Python. Thanks

I hesitate to put this in an answer, but it's the only way to illustrate what I'm talking about. In R, we would take hierarchical data like what you provided and store it like this:

df <- data.frame(grp1 = 'a1',
                 grp2 = rep(c('b1','b2'),each = 4),
                 grp3 = rep(c('c1','c2','c3','c4'),times = 2))
> df
  grp1 grp2 grp3
1   a1   b1   c1
2   a1   b1   c2
3   a1   b1   c3
4   a1   b1   c4
5   a1   b2   c1
6   a1   b2   c2
7   a1   b2   c3
8   a1   b2   c4

If you have further groups, or levels, you'd add more columns and replicate the previous columns as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM